The std::move function
The std::move function aims at implementing move semantics. The function receives a forwarding reference to an object and returns an rvalue reference to this object. One of the possible implementations of std::move looks as follows:
template<typename T>
std::remove_reference_t<T>&& move(T&& x)
{
return static_cast<std::remove_reference_t<T>&&>(x);
}
lvalue and rvalue references can be passed to the std::move function, and an rvalue reference must be obtained as a result. Therefore, to denote the return type, we first use the std::remove_reference_t trait, that simplifies the template type T to a usual non-reference type. Then we explicitly add '&&'. Let's take a look at the following code fragment:
std::vector<int> &vec1 = DoSomeCalculations();
std::vector<int> vec2 = std::move(vec1);
Here's what we have here:
- An instance of the std::move function is instantiated with template type T = std::vector<int> & .
- This instance takes an argument of the std::vector<int> & type. When trying to form an argument as an rvalue reference to std::vector<int> &, the compiler uses reference collapse, and the result argument type is equivalent to std::vector<int> &. This is an lvalue reference to vector<int>.
- The std::remove_reference_t trait returns the std::vector<int> type simplified to a non-reference type. '&&' is added to std::vector<int>. As a result, the return type of std::vector<int> && is an rvalue reference to vector<int>.
Now let's consider the case when an rvalue reference is passed to std::move:
std::vector<int> &&vec1 = DoAnotherCalculations();
std::vector<int> vec2 = std::move(vec1);
Here's what happens:
- An instance of the move function with template type T = std::vector<int> is instantiated.
- This instance receives an argument of the std::vector<int> && type. It is an rvalue reference on vector<int>.
- The std::remove_reference_t trait returns the std::vector<int> type simplified to a non-reference type. '&&' is added to std::vector<int>. As a result, the return type of std::vector<int> && is an rvalue reference to vector<int>.
The std::move call results in an xvalue. This means that the resources of such an object can be reused. If it's possible, move semantics (not the copy semantics) is applied for an xvalue expression. For example, if the result of the std::move function is assigned to some obj object of the type type, then the move assignment operator is called (if it is defined for type).
Additional links:
0