explicit copy constructors

D

Dave

Hello NG,

Can anybody fathom the purpose of an explicit copy constructor? On page 232
of the Josuttis STL reference, I see a reference to such.

How could you ever need to supress the possibility of an implicit conversion
from type T to type T? Such an implicit conversion could never occur
because you're already of the required type!

Thanks,
Dave
 
V

Victor Bazarov

Dave said:
Can anybody fathom the purpose of an explicit copy constructor? On page 232
of the Josuttis STL reference, I see a reference to such.

How could you ever need to supress the possibility of an implicit conversion
from type T to type T? Such an implicit conversion could never occur
because you're already of the required type!

IIRC, an explicit copy constructor would prevent copying in certain
cases. I strongly urge you to look in the archives about 'explicit'.
I do remember some interesting discussions in c.l.c++.moderated about
'explicit' keyword and its use for non-conversion constructors.

V
 
I

Ioannis Vranos

Dave said:
Hello NG,

Can anybody fathom the purpose of an explicit copy constructor? On page 232
of the Josuttis STL reference, I see a reference to such.

How could you ever need to supress the possibility of an implicit conversion
from type T to type T? Such an implicit conversion could never occur
because you're already of the required type!


When such conversion produces undesirable results, as in the case of
containers.


Check TC++PL 11.7.1, on page 284. A quote from there:


"By default, a single argument constructor also defines an implicit
conversion. For some types, that is ideal. For example:

complex z = 2; // initialize z with complex(2)


In other cases, the implicit conversion is undesirable and error-prone.
For example:

string s= ´a´; // make s a string with int(’a’) elements

It is quite unlikely that this was what the person defining s meant.


Implicit conversion can be suppressed by declaring a constructor
explicit. That is, an explicit constructor will be invoked only
explicitly. In particular, where a copy constructor is in principle
needed (11.3.4), an explicit constructor will not be implicitly invoked."
 

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

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top