Topic: explicit" copy constructors
Author: "Andrei Alexandrescu (See Website for Email)"
Date: Sat, 7 Aug 2004 14:30:53 +0000 (UTC) Raw View
[preserved the entire body of the message to bring context to the now
crossposted comp.std.c++]
"John Potter" <jpotter@falcon.lhup.edu> wrote in message
news:DELPc.7744$Jp6.2586@newsread3.news.atl.earthlink.net...
> On 3 Aug 2004 07:36:43 -0400, "Andrei Alexandrescu \(See Website for
> Email\)" <SeeWebsiteForEmail@moderncppdesign.com> wrote:
>
> > "John Potter" <jpotter@falcon.lhup.edu> wrote in message
> > news:3dsPc.23068$iK.2280@newsread2.news.atl.earthlink.net...
> > > IMO. Never ever even think about making a copy ctor explicit.
>
> > Why so? If you are designing a class hierarchy, in the overwhelming
majority
> > of designs you want to avoid slicing, and instead only manipulate
objects in
> > the hierarchy through (smart) pointers.
>
> > In such a case, it makes a ton of sense to make the copy constructor
> > explicit. No?
>
> Slicing is still allowed. It prevents all pass by value whether sliced
> or not. It allows simulation of pass by value whether sliced or not.
> At least VC++ still thinks that explicit on a copy ctor should have no
> effect. There are reasonable people that agree with that.
That's why I crossposted csc++. The standard must have some say in that...
but I can't think of any. I take it it's just the natural behavior of
explicit we can count on?
> Can you give a complete example of a simple hierarchy where an explicit
> copy ctor plays an essential role? Also, explain the role for those of
> us who may be slow?
If anyone, it's me who's slow. Today's technique for protecting against
involuntary slicing is to make the copy constructor protected. That must be
done throughout the hierarchy. Making the constructor explicit instead would
be a lower form of protection because client code can always slice if they
want to.
However, making the copy constructor *both* protected and explicit is best
either. This is because client code can't copy due to the "protected", and
derived classes can't accidentally pass by value due to "explicit".
This all, of course, is based on the assumption that in a class hierarchy
you want to preserve dynamic polymorphism and as such you don't want to copy
an object unwittingly.
Andrei
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.jamesd.demon.co.uk/csc/faq.html ]