Re: Copy constructor not called
Francis Glassborow ha scritto:
In article <Rz84h.33674$Fk1.67319@twister2.libero.it>, Alberto Ganesh
Barbati <AlbertoBarbati@libero.it> writes
The sentence "A non-template constructor for class X is a copy
constructor [...]" appears in normative text (?12.8/2), not in the
footnote I quoted. According to me it definitely means that a template
can't be a copy ctor and the footnote just rephrase that in a clearer
way. What makes you say that a template can be a copy ctor?
#include <iostream>
struct x {
x(){}
x(x &){std::cout << "copy ctor used\n";}
template <typename T>
x(T &){std::cout << "template used\n";}
};
int main(){
x y;
x const cy;
x z(y);
x cz(cy); // A
}
Consider how line A is compiled
Now change the definition of the copy ctor to take a x const & and
rerun. Note the change in output. So how is the template not generating
a copy ctor except in the limited sense that its existence does not
inhibit the compiler generation of a copy ctor if the user does not
provide one.
I don't see how this argument supports your claim.
Line A is a direct initialization, so it can use whatever matching
constructor it finds. The chosen constructor does not have to be a copy
constructor. Moreover, the mere fact that some specific constructor is
being chosen to implement "T t(u)" does not allow you to call it "copy
constructor" regardless of the fact that it actually looks like it's
making a copy.
A copy constructor is not just a constructor able to make a copy or that
looks like it's doing a copy. It a "special member function" (?12/1). In
addition to being implicitly generated if necessary, special member
functions can also be called implicitly. In the particular case of the
copy constructor, there are contexts (for example while handling
exceptions) where no other constructor is considered. But, according to
me, the ultimate distinguishing difference between copy constructors and
non-copy constructors is that a call to a copy constructor can sometimes
be elided even if the copy constructor has side-effects. This never
occurs for non-copy constructors. So in the example above, you may not
see "copy ctor used" even if the copy constructor is used, but you will
always see "template used" if the templated constructor is used.
Ganesh
PS: notice that paragraph ?12.1/10, which was contradicting ?12.8/2 by
not restricting to non-templates, has been amended in the most recent
draft of the standard.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]