Neither copy nor move constructor called [duplicate]

允我心安 提交于 2019-12-24 21:15:31

问题


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



来源:https://stackoverflow.com/questions/13567029/neither-copy-nor-move-constructor-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!