Say, I have a class with a movable resource as its member:
struct A {
std::vector<int> v;
};
There is an implicitly generated copy constructor, which works perfectly and is implemented roughly like this:
// Implicitly generated copy constructor
A(const A& rhs) : v(rhs.v) {};
And I expect a move constructor to be implicitly generated the same way in C++11:
// Move constructor is not implicitly generated, why?
A(A&& rhs) : v(std::move(rhs.v)) {};
However, no move constructor is implicitly generated, at least in Visual Studio 2010. And a vector is copied in the following code:
A a;
A b(std::move(a)); // a.v is copied, not moved
My question is - why? For my point of view, there is no difference for the compiler to implicitly generate copy of move constructor - it has full information for both of these.
Or maybe move constructor should be generated by the standard, but Visual Studio doesn't do this?
Update
I debugged the code, and the vector(const _Myt& _Right)
constructor is called in <vector>
file. When I write move constructor explicitly, the vector(_Myt&& _Right)
constructor is called.
Update2
Just checked it: the same behavior in Visual Studio 2012 Update 1.
Update3
Ok, I agree this is a duplicate, but the link provided in the close reason is incorrect. Correct link is provided in the comments: Why is this copy constructor called rather than the move constructor?
And here is why, from the VC blog:
Rvalue references v3.0 adds new rules to automatically generate move constructors and move assignment operators under certain conditions. This will not be implemented in VC11, which will continue to follow VC10's behavior of never automatically generating move constructors/move assignment operators. (As with all of the not-yet-implemented features here, this is due to time and resource constraints, and not due to dislike of the features themselves!)