Address of the object returned by the value from the function

Given the following minimum code:

class MyClass {
    public:
    MyClass() {}
};

MyClass myfunc() {
    MyClass obj;
    cout << "Address of obj in myFunc " << &obj << endl;
    return obj;
}

int main() {
    MyClass obj(myfunc());
    cout << "Address of obj in main   " << &obj << endl;
    return 0;
}

I get the following output:

Address of obj in myFunc 0x7fff345037df
Address of obj in main   0x7fff3450380f

Now, just adding a destructor to MyClass, I get the following output:

Address of obj in myFunc 0x7fffb6aed7ef
Address of obj in main   0x7fffb6aed7ef

Showing that both objects are now the same ... Is it just a coincidence ?!

In addition, what exactly happens in:

MyClass obj(myfunc());

I overloaded the copy constructor to print the message, but it never appears ...

+4
source share
1 answer

By adding a destructor (no matter what you actually did, you are not showing the code), the behavior has changed to using Return Value Optimization , called RVO.

, , , , .

RVO. RVO . RVO , , , RVO.

+6

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


All Articles