Why is copy-constructor not being called, but is the default constructor being called in this code?

I have an understanding that the copy constructor will be called when the object is created from an existing object, and also when the function returns the object by value. So why in the code below 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
}
0
source share
1 answer

Short answer: compiler optimization.

  • a main, ( ++ 11) return. .

  • class A a = A(), a , . copy elision.

, ( ) , .

+3

Source: https://habr.com/ru/post/1527468/


All Articles