问题描述:

Considering the following minimal 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 obtain the following output:

Address of obj in myFunc 0x7fff345037df

Address of obj in main 0x7fff3450380f

Now, just by adding a destructor in 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 this just a coincidence ?!

Also, what does exactly happen in:

MyClass obj(myfunc());

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

网友答案:

By adding a destructor (whatever it was that you actually did, you're not showing the code) the behavior changed to use Return Value Optimization, known as RVO.

Then a pointer to the caller's storage is passed to the function, and the function constructs the object directly in that storage, instead of e.g. copying a value in a processor register or set of registers.

The same calling convention, with a hidden result storage pointer, can also be used without RVO. Without RVO a copy or move is performed at the end of the function. The standard supports RVO optimization under certain conditions, but, while it can be reasonably expected, a compiler is not under any obligation to perform RVO.

相关阅读:
Top