I have this piece of code. I expected to d3
be created using the move constructor since I passed the temporary rvalue value.
#include <iostream>
using namespace std;
struct Data {
Data(): x(1)
{
cout << "constructor" << endl;
}
Data(const Data& original): x(2)
{
cout << "copy constructor" << endl;
}
Data(Data&& original): x(3)
{
cout << "move constructor" << endl;
}
int x;
};
int main() {
Data d1;
cout << "d1:" << d1.x << endl << endl;
Data d2(d1);
cout << "d2:" << d2.x << endl << endl;
Data d3(Data{});
cout << "d3:" << d3.x << endl << endl;
Data d4(move(Data{}));
cout << "d4:" << d4.x << endl << endl;
return 0;
}
I saw the result as:
constructor
d1:1
copy constructor
d2:2
constructor
d3:1
constructor
move constructor
d4:3
Although d4
created with the move constructor, as I expected, I donβt understand why I d3.x
got the value 1. It seems that it was d3
built by the default constructor?
source
share