Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When will c++11 perform move automatically when std::move is not explicitly used?

If I have a struct in which I did not provide any copy and move constructor:

struct MyStruct {
  MyStruct() { // this is the only function
    ...
  }
  ...
};

then if I do the following:

std::vector<MyStruct> vec;
...
vec.push_back(MyStruct());

instead of using std::move() like the followings:

vec.push_back(std::move(MyStruct()));

Will c++11 smartly do the move for my temporary variable? Or, how can I make sure it is a move instead of a copy?

like image 624
keelar Avatar asked Aug 06 '14 07:08

keelar


2 Answers

In C++11 std::vector::push_back will use a move constructor if passed an rvalue (and a move constructor exists for the type), but you should also consider using std::vector::emplace_back in such situations; std::vector::emplace_back will construct the object in place rather than moving it.

like image 66
dustyrockpyle Avatar answered Sep 28 '22 07:09

dustyrockpyle


Will c++11 smartly do the move for my temporary variable? Or, how can I make sure it is a move instead of a copy?

It depends. This

vec.push_back(MyStruct());

will bind to

std::vector<MyStruct>::push_back(MyStruct&&);

but whether the rvalue passed is moved or copied depends fully on whether MyStruct has a move copy constructor (likewise for move assignment).

It will make absolutely no difference if you call

vec.push_back(std::move(MyStruct()));

because MyStruct() is already an rvalue.

So it really depends on the details of MyStruct. There is simply not enough information in your question to know if your class has move constructor.

These are the conditions that must be met for a class to have an implicitly generated move constructor:

  • no user-declared copy constructors
  • no user-declared copy assignment operators
  • no user-declared move assignment operators
  • no user-declared destructors

Of course, you can always provide your own if any of these conditions are not met:

MyStruct(MyStruct&&) = default;
like image 35
juanchopanza Avatar answered Sep 28 '22 07:09

juanchopanza