The presence of a copy constructor causes the function to return by reference instead of a value

In the following code, it prints two different memory locations. This makes sense to me as I return by value.

#include <iostream> using namespace std; class Foo { public: Foo () {} // Foo (const Foo &) { cout << "Copy con" << endl; } }; Foo test () { Foo foo; cout << &foo << endl; return foo; } int main () { Foo foo = test(); cout << &foo << endl; } 

However, if I uncomment the copy constructor in the above code and run it again, it will issue the same memory cell twice. What for? It does not print "Copy con" at all, so I know that the copy constructor is not called. It seems that just having a copy constructor causes some optimization, even if it is not called.

I am compiling with "g ++ -Wall test.cpp -o test" in GCC 4.6.3.

+4
source share
1 answer

This is the result of optimizing the return value . Basically, your compiler eliminates the expensive copy operation caused by the return statement, although the copy constructor has side effects.

The reason for this is that returning a complex object is costly. Instead of wasting time copying, the compiler secretly creates a hidden object in the stack stack of the caller and passes a link to this hidden object of the called function, and the return value of the function is copied directly to this hidden object.

The C ++ standard states this explicitly (ISO-IEC 14882: 2011 12.8, clause 31):

When certain criteria are met, an implementation may skip copying / moving an object of the class, even if copying / moving the constructor and / or destructor of the object have side effects.

+2
source

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


All Articles