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) );
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,
pris not an rvalue, so you won’t get it moved.However, if you – for example – pass a temporary object to the vector, like this:
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:
Note, however, that in this case you won’t be able to use
prafter 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_backthis is indeed the case.)