Re: copy ctor and 'explicit' qualifier
On Mar 31, 7:41 pm, Andrey Tarasevich <andreytarasev...@hotmail.com>
wrote:
subramanian10...@yahoo.com, India wrote:
copy ctor of a class is NOT declared with 'explicit'
qualifier because if it is declared 'explicit', then the
class cannot be used with standard library container. Is
this reasoning correct ? Or is there some other reason for
NOT declaring the copy ctor with 'explicit' qualifier ?
Declaring the copy-constructor 'explicit' will essentially
prevent any form of copy-initialization, because the copying
in the copy-initialization is always implicit. (Maybe I'm
missing something, but right away I can't think of any way to
express copy-construction in copy-initialization
_explicitly_).
To tell the truth, logically, I would think that using
copy-initialization is saying explicitly that I want a copy.
The standard, however, says quite explicitly: "An explicit
constructor constructs objects just like non-explicit
constructors, but does so only where the direct-initialization
syntax or where casts are explicitly used." So if T has an
explicit copy constructor, and u is an object of type T:
T t( u ) ; // legal
T t = u ; // illegal
despite the fact that in =A78.5 it says that if the types are the
same, copy initialization and direct initialization have the
same semantics.
This means that it will become impossible to copy-initialize
objects of this class (regardless of whether the
initialization requires a conversion), pass these objects to
functions (pass "by value" that is), return them from
functions, throw them as exceptions etc.
At the same the copy-constructor will still work in
direct-initialization contexts.
I wouldn't say that declaring the copy-constructor 'explicit'
will make it unusable with STL containers. The
'CopyConstructible' requirement imposed on the container
element type is expressed in terms of direct-initialization,
which should not be affected by 'explicit' (assuming that the
container implementation is done correctly). The only thing
that will be disabled by this is the default argument support
for those container member functions that use them.
That's true today, but the latest draft for the next version
says specifies:
T t = u ;
as a requirement for CopyConstructible, which means that the
copy constructor cannot be explicit.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34