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.
source share