Why copy-constructor is not called but default constructor is invoked in this code? [duplicate]

别来无恙 提交于 2020-01-06 12:42:42

问题


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 the main 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 the a 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!