C++ Primer, Fourth Edition

H

huangshan

hi all

I read "C++ Primer, Fourth Edition" ,
but can't understand this sentence
"By making the parameters const references, we allow types that do not allow
copying."
in "16.1. Template Definitions" .

who can tell me?
thanks
 
D

Daniel T.

"huangshan said:
hi all

I read "C++ Primer, Fourth Edition" ,
but can't understand this sentence
"By making the parameters const references, we allow types that do not allow
copying."
in "16.1. Template Definitions" .

who can tell me?

class NonCopyable {
NonCopyable( const NonCopyable& );
NonCopyable& operator=( const NonCopyable& );
public:
NonCopyable();
};

void fn1( NonCopyable nc ); // this will fail to compile
void fn2( const NonCopyable& nc ); // this will compile
 
V

Victor Bazarov

huangshan said:
hi all

I read "C++ Primer, Fourth Edition" ,
but can't understand this sentence
"By making the parameters const references, we allow types that do
not allow copying."
in "16.1. Template Definitions" .

who can tell me?

class NoCopies {
NoCopies(NoCopies const&); // copying prohibited
public:
NoCopies(int);
};

void foo(NoCopies);
void bar(const NoCopies&);

int main()
{
NoCopies nc(42);
foo(nc); // error -- must be able to copy
bar(nc); // no error
}

V
 
A

Alf P. Steinbach

* Victor Bazarov:
class NoCopies {
NoCopies(NoCopies const&); // copying prohibited
public:
NoCopies(int);
};

void foo(NoCopies);
void bar(const NoCopies&);

int main()
{
NoCopies nc(42);
foo(nc); // error -- must be able to copy
bar(nc); // no error
}

Just to fill out the picture, the /current/ standard doesn't allow

bar( NoCopies( 42 ) );

because in the current standard, when binding a temporary to a reference
to const, the compiler is allowed to copy the temporary any number of
times, i.e. a copy constructor must be available.

So the phrasing "allow types that do not allow copying" allows an
interpretation where one believes more is allowed than is actually
allowed, but, types that do not allow copying are allowed as far as the
current standard allows (heh).

As I understand it this will be fixed in C++0x.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top