copy initialization : why move or copy constructor was not called even if copy-elision is turned off?

最后都变了- 提交于 2019-12-10 17:12:15

问题


My question is different because I may "know" copy-elision. I am learning copy initialization. However,the following code confused me because I have already turned off the copy-elision using -fno-elide-contructors -O0 option.

#include <iostream>
using namespace std;
class test{
public :
    test(int a_, int b_) : a{a_}, b{b_} {}
    test(const test& other)
    {
        cout << "copy constructor" << endl;
    }
    test& operator=(const test& other)
    {
        cout << "copy assignment" << endl;
        return *this;
    }
    test(test&& other)
    {
        cout << "move constructor" << endl;
    }
    test& operator=(test&& other)
    {
        cout <<"move assignment" << endl;
        return *this;
    }

private :
    int a;
    int b;
};

test show_elide_constructors()
{
    return test{1,2};
}

int main()
{
    cout << "**show elide constructors**" <<endl;
    show_elide_constructors();
    cout << "**what is this?**" <<endl;
    test instance = {1,2};//why neither move constructor nor copy constructor is not called?
    cout << "**show move assignment**" <<endl;
    instance = {3,4};
    return 0;
}

I first build with the command: g++ -std=c++11 -fno-elide-constructors -O0 main.cpp -o main and I got the result as following:

**show elide constructors**
move constructor
**what is this?**
**show move assignment**
move assignment

Then I built with command without -fno-elide-constructor -O0 option to attest that g++ indeed turned off the optimization in my previous build.

So, why test instance = {1,2} does not call copy constructor or move constructor? Isn't a temp object created from the implicit conversion? And instance is supposed to be initialized by that temp object?


回答1:


why test instance = {1,2} does not call copy constructor or move constructor?

It shouldn't. test instance = {1,2} is copy-list-initialization, as the effect, the appropriate constructor (i.e. test::test(int, int)) is used to construct the object instance directly. No needs to construct a temporary and call copy/move constructor here.




回答2:


OK. I add some supplementary information here. : Copy initialization, List initialization.

So T object = {other} is indeed copy initialization until c++11, which consider it as list initialization.



来源:https://stackoverflow.com/questions/51257847/copy-initialization-why-move-or-copy-constructor-was-not-called-even-if-copy-e

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