jeudi 26 février 2015

Move constructor isn't called by the return operator without std::move()


I'm reading "The C++ Programming Language", 2013 by Stroustrup, and I assumed that when we return some object from function by value, move constructor should be called automatically, because the compiler clearly knows that object being returned will never be used.


In the section 3.3.2 "Moving Containers" we have this example:



Vector f()
{
Vector x(1000);
Vector y(1000);
Vector z(1000);
// ...
z = x; // we get a copy
y = std::move(x); // we get a move
// ...
return z; // we get a move
};


And a bit of clarification below:



When z is destroyed, it too has been moved from (by the return) so that, like x, it is empty (it holds no elements).



But my experiment shows it is not true. Simple program:



#include <iostream>

using namespace std;

class MyClass {
int value;

public:
explicit MyClass(int value)
: value {value}
{
cout << "ctor value " << value << '\n';
}

MyClass(const MyClass &src)
: value {src.value}
{
cout << "ctor copy " << value << '\n';
}

MyClass(MyClass &&src)
: value {src.value}
{
cout << "ctor move " << value << '\n';
}

~MyClass(){
cout << "dtor " << value << '\n';
}

int getValue() const
{
return this->value;
}

};

MyClass test(void)
{
MyClass x {10};
return x;
}

int main()
{
MyClass z = test();
}


I expected test() to call move constructor on return, but in fact neither copy nor move constructor isn't called, here's the output:



ctor value 10
dtor 10


(Re-checked by gcc 4.9.2 here: http://ift.tt/1DfurCQ )


But if I explicitly specify that x is movable, like this:



MyClass test(void)
{
MyClass x {10};
return move(x);
}


Then it works as I expect it to:



ctor value 10
ctor move 10
dtor 10
dtor 10


Have I missed something?




Aucun commentaire:

Enregistrer un commentaire