What

It was designed to move objects, whose lifetime expires, instead of copying them. The data is transferred from one object to another.

rvalues such as return value or calculated value (string +) can now be moved instead of copy.

How

To implement it, rvalue references, move constructors, and the move assignment operator were added. Also, some functions were added to the STL to support move semantics. For example, std::move and std::forward.

#include <utility>
template <typename T>
void Swap(T &lhs, T &rhs) noexcept
{
	T t = std::move(lhs);
	lhs = std::move(rhs);
	rhs = std::move(t); 
}

Why

  • Turning expensive copies into cheap moves.
  • Implementing safe “move-only” types; that is, types for which copying does not make sense, but moving does. Examples include locks, file handles, and smart pointers with unique ownership semantics.
std::vector<int> arrA(1'000'000, 0);
std::vector<int> arrB(1'000'000, 1);
Swap(arrA, arrB);

Two objects of the std::vector<int> type are created. Each contains 1’000’000 elements. Then the Swap function swaps them. The std::vector class template contains a non-trivial copy constructor that has the following functions:

  • performs dynamic memory allocation to the desired number of elements;
  • makes a deep copy of the elements from the passed std::vector.

As a result, we have 3’000’000 copies of int type objects. The situation may get even worse if std::vector is instantiated by a non-trivially copied type.