I'm studying C++11 and I don't understand why in the following code
class X
{
std::vector<double> data;
public:
// Constructor1
X():
data(100000) // lots of data
{}
// Constructor2
X(X const& other): // copy constructor
data(other.data) // duplicate all that data
{}
// Constructor3
X(X&& other): // move constructor
data(std::move(other.data)) // move the data: no copies
{}
X& operator=(X const& other) // copy-assignment
{
data=other.data; // copy all the data
return *this;
}
X& operator=(X && other) // move-assignment
{
data=std::move(other.data); // move the data: no copies
return *this;
}
};
X make_x() // build an X with some data
{
X myNewObject; // Constructor1 gets called here
// fill data..
return myNewObject; // Constructor3 gets called here
}
int main()
{
X x1;
X x2(x1); // copy
X x3(std::move(x1)); // move: x1 no longer has any data
x1=make_x(); // return value is an rvalue, so move rather than copy
}
in the line
return myNewObject; // Constructor3 gets called here
the Constructor3 gets called. Why?