The std::move()
operator is a cast that gets an xvalue reference to an object, allowing it to be moved. Moving the object instead of copying it increases efficiency.
For example, consider the following swap()
function:
template <typename T> void swap(T& a, T& b) { T tmp(a); a = b; b = tmp; }
When this runs, a
is first copied to tmp
, then b
is copied to a
, and finally tmp
is copied to b
. If a
and b
were expensive objects to copy, this would be very inefficient.
With move(),
we can rewrite the swap()
function this way:
#include <utility> template <typename T> void swap(T& a, T& b) { T tmp(std::move(a)); a = std::move(b); b = std::move(tmp); }
Now if a
and b
are of a class that has a move constructor and assignment operator, they will be efficiently moved rather than copied.