2

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!)

Community
  • 1
  • 1
Mikhail
  • 20,685
  • 7
  • 70
  • 146
  • 1
    How are you coming to the conclusion that no move constructor is generating? – Andy Prowl Apr 06 '13 at 14:37
  • I have a feeling that std::vector does not have trivial constructors, and for that reason implicit move constructors are not generated here. However, I cannot find a reference for this. – Andres Jaan Tack Apr 06 '13 at 14:44
  • 2
    Looks like this is a [known bug](http://stackoverflow.com/questions/8991874/why-is-this-code-trying-to-call-the-copy-constructor). – Andy Prowl Apr 06 '13 at 14:45
  • 1
    Another similar question http://stackoverflow.com/questions/10201659/why-is-this-copy-constructor-called-rather-than-the-move-constructor?rq=1 – balki Apr 06 '13 at 14:49

0 Answers0