0

Possible Duplicate:
Why copy constructor is not called in this case?
What are copy elision and return value optimization?

Can anybody explain to me why the following program yields 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 arised when I tried to figure out seemingly strange outcome of this example: move ctor of class with a constant data member or a reference member

Community
  • 1
  • 1
JohnB
  • 13,315
  • 4
  • 38
  • 65
  • 2
    who's the first to find the duplicate? check RVO – BЈовић Nov 26 '12 at 14:38
  • 2
    Let's start searching from here: http://stackoverflow.com/questions/1758142/why-copy-constructor-is-not-called-in-this-case :) – kennytm Nov 26 '12 at 14:39
  • 3
    This is **Copy Elision** due to **Return Value Optimization(RVO)** there can be many spices added to this curry but the main ingredient is still RVO and copy elision. – Alok Save Nov 26 '12 at 14:40

1 Answers1

7

The compiler is free to elide copy and move construction, even if these have side effects, for objects it creates on it own behalf. Temporary objects and return values are often directly constructed on the correct location, eliding copying or moving them. For return values you need to be a bit careful to have the elision kick in, though.

If you want to prevent copy elision, you basically need to have two candidate objects conditionally be returned:

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

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

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
  • Thank you. It's hard to google when I don't know what to google for. – JohnB Nov 26 '12 at 14:49
  • And in one case, elide copies for objects it doesn't create on its own behalf. That case is `Foo f() { Foo a; return a; } ... Foo f = f();`. There is still permitted to be no copy/move, thanks to NRVO. `a` and `f` are variables in different functions, but can still be conflated to a single object by copy elision (along with the temporary which is the return value of `f`). – Steve Jessop Nov 26 '12 at 14:54
  • Actually this new code will *always* produce a copy, regardless of how smart compilers get, as copy-elision is not allowed in the construction of the return value from `a` (because the return expression contains more than *just* "`a`"). Furthermore, there is a simpler way to stop copy-elision -- `return static_cast(A());` (This binds the temporary to a reference, and thus disqualifies it from copy-elision). – Mankarse Nov 26 '12 at 15:03