consider the following:
class X {
public:
X(int i) { cout << "X(int i)" << endl; }
X(const X& x) { cout << "X(const X& x)" << endl; }
};
void main() {
X x1(1);
X x2 = X(1);
X x3 = (X)1;
}
running this code produces this output:
X(int i)
X(int i)
X(int i)
I thought that all of the above three statements are equivalent as the copy CTOR is never called. However, changing X
's copy CTOR to be private:
class X {
public:
X(int i) { cout << "X(int i)" << endl; }
private:
X(const X& x) { cout << "X(const X& x)" << endl; }
};
Will fail to compile (In visual studio 2010) with this error:
cannot access private member declared in class 'X'
So it seems the copy CTOR is involved somehow though I don't quite understand how.
T开发者_如何学Gohanks
X x1(1);
X x2 = X(1);
X x3 = (X)1;
The reason is that all of these are not exactly equivalent.
First one is direct-initialization, while the second and third is copy-initialization. For copy-initialization, copy-constructor must be public, or else compiler will give error.
Now the question is, if 2nd and 3rd requires the copy-ctor to be public,then why the following output:
X(int i)
X(int i)
X(int i)
This surely says that copy-ctor is never called which is true. Compiler just elided the call to copy-ctor. According to §8.5/14, in such cases, the compiler is permitted to eliminate the need to call copy-constructor. That is why you don't see copy-ctor being called.
A little inside : in the 2nd and 3rd case, first a temporary is created by calling X(int i)
, then this temporary was supposed to be passed to the copy-ctor to copy-initialize the object being declared. But the compiler optimizes away this step, eliding the call to copy-ctor.
The X x2 = ...
invokes the copy constructor (even if the compiler optimises it out later). Thus, it must still be accessible.
This :
X x3 = (X)1; is c-style cast from
int
into the object of typeX
This copying :
X x2 = X(1);
is optimized away but the compiler still needs the access to the copy-constructor.
Ist object makes use of parrametrized constructor as you know it and all others are using copy constructor. i.e. why when you are makin it private access violation occurs. The others two objects are making use of copy constructor.
These are the way of using copy constructor.
精彩评论