Search code examples
c++c++11move-semanticsrvalue-referencelvalue

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?


Solution

  • 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.