Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 591
Han XIAO Avatar asked Mar 05 '23 20:03

Han XIAO


1 Answers

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.

like image 155
songyuanyao Avatar answered Apr 27 '23 00:04

songyuanyao