Frage

I tested the behavior of copy constructor with functions that return an object by value, and I came across a case where copy constructor does get invoked and a case it doesn't.

Please consider the following code:

class A {
public:
    A() {}
    A(const A& a) {
        cout << "Copy CTOR: " << "This address is " << this 
             << " input address is "<< &a <<       "\n";
    }
};

A returnMyself(A& a) {
    cout<<"Myself address is: "<< &a << "\n";
    return a;
}

A returnLocal(A& a) {
    A local;
    cout<<"local address in returnLocal is  "<< &local << "\n";
    return local;
}

int main () {
    A a;
    cout<<"Before returnMyself\n";
    returnMyself(a);
    cout<<"After returnMyself\n\n";

    cout<<"Before returnLocal\n";
    returnLocal(a);
    cout<<"After returnLocal\n";
}

The output of main is:

Before returnMyself.
Myself address is: 0x7fff6afd88f0.
Copy CTOR Invoked: This address is 0x7fff6afd88d8. Input address is 0x7fff6afd88f0.
After returnMyself.

Before returnLocal.
Local address in returnLocal is  0x7fff6afd88d0.
After returnLocal.

As you can see, when I declare a local object and return it, copy constructor doesn't get invoked, as opposed to returning a given reference-object which does invoke copy constructor.

Does anyone have an explanation for this? In general, what are the cases of invoking copy constructor from a function that returns-by-value?

Thanks!

War es hilfreich?

Lösung

This is copy elision. The compiler is clever enough to optimize that copy away.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top