Neither copy nor move constructor called [duplicat

2019-09-09 08:30发布

问题:

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

回答1:

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).