0

For example:

std::vector<std::pair<std::string, bool > > v;
std::pair<std::string, bool> pr;
v.push_back( pr );

Assuming std::pair has defined a move assignment operator. Will the call to v.push_back automatically use the move assignment or I need to specifically ask for it like so?

v.push_back( std::move(pr) );
user841550
  • 1,067
  • 3
  • 16
  • 25
  • Is this a duplicate of http://stackoverflow.com/questions/9724856/c11-do-move-semantics-get-involved-for-pass-by-value? – jogojapan Nov 16 '12 at 03:19

1 Answers1

1

You will only get a move if the argument of the function (in this case, the argument of push_back) is an rvalue, as well as in certain situations when you return objects from a function.

In your example, pr is not an rvalue, so you won't get it moved.

However, if you – for example – pass a temporary object to the vector, like this:

v.push_back(std::pair<std::string,bool>());

This will be an rvalue and trigger a move.

You can also trigger the move by explicitly casting the argument to an rvalue in the way you suggested:

v.push_back(std::move(pr));

Note, however, that in this case you won't be able to use pr after the call in a meaningful way any more as its contents have been moved away.

(Of course, another precondition for a move is that the function you call actually accepts rvalue references. For vector push_back this is indeed the case.)

jogojapan
  • 68,383
  • 11
  • 101
  • 131
  • OK so in my example I have to call std::move if I want to get move semantics, correct? – user841550 Nov 16 '12 at 03:20
  • Yes. Note that after that, you won't be able to use `pr` in a meaningful way any more (because its contents have been moved). – jogojapan Nov 16 '12 at 03:21
  • Understood and it's fine since pr would be a temporary object I cosrtruct on the stack in order to pass to another function and have no use with it after – user841550 Nov 16 '12 at 03:25
  • That's perfectly reasonable, then. Alternatively, though, you may want to consider putting the code that creates the temporary object into a function, say `pair create()`, which simply returns `pr` when its ready, and then call `push_back` like this: `v.push_back(create());`. In this case you will get `pr` moved out of the function and into the vector without ever using `std::move` because of the special rules that apply to how movable objects are returned by value. – jogojapan Nov 16 '12 at 03:29