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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With