问题
I have an understanding that copy constructor will be called when an object is created from an already existing object and also when a function returns object by value. So why in the below code the copy constructor is not called but the default constructor?
class A {
public:
A() { cout << "A" << endl; }
A(A &) { cout << "A&" << endl; }
A(const A &) { cout << "const A&" << endl; }
};
A fun() {
class A a;
return a;
}
int main() {
class A a = fun(); // output: A
}
回答1:
Short answer: compiler optimizations.
First, the
a
object from your function is created directly in the scope of themain
function, in order to avoid having to copy (or move in C++11) the local parameter out of the scope of the function via the function's return. This is return value optimization.Then, in main, the statement becomes equivalent to
class A a = A()
and again the compiler is allowed to the create thea
object in place, without copying from a temporary object. This is copy elision.
This is allowed even if the copy constructor (which is bypassed entirely) has side-effects, like in your example.
来源:https://stackoverflow.com/questions/21700107/why-copy-constructor-is-not-called-but-default-constructor-is-invoked-in-this-co