Neither copy nor move the constructor called

Possible duplicate:
Why is the copy constructor not called in this case?
What is optimization when copying and returning values?

Can someone explain to me why the following program gives the output "cpy: 0" (at least when compiled with g ++ 4.5.2):

#include<iostream> struct A { bool cpy; A() : cpy (false) { } A (const A & a) : cpy (true) { } A (A && a) : cpy (true) { }; }; A returnA () { return A (); } int main() { A a ( returnA () ); std::cerr << "cpy: " << a.cpy << "\n"; } 

The question arose when I tried to figure out the apparently strange result of this example: move the class ctor with a constant data member or reference element

0
source share
1 answer

The compiler can freely copy and move the construct, even if they have side effects, for the objects that it creates on its behalf. Temporary objects and return values ​​are often directly built in the right place, speeding up their copying or moving. For return values, you need to be a little careful to be able to execute an ellipse.

If you want to exclude copying, you need to conditionally return two candidate objects:

 bool flag(false); A f() { A a; return flag? A(): a; } 

Assuming you don't change the flag , this will always create a copy of a (unless the compilers have become smarter since the last time I tried).

+6
source

All Articles