function template
<utility>

std::move

template <class T>typename remove_reference<T>::type&& move (T&& arg) noexcept;
Move as rvalue
Returns an rvalue reference to arg.

This is a helper function to force move semantics on values, even if they have a name: Directly using the returned value causes arg to be considered an rvalue.

Generally, rvalues are values whose address cannot be obtained by dereferencing them, either because they are literals or because they are temporary in nature (such as values returned by functions or explicit constructor calls). By passing an object to this function, an rvalue that refers to it is obtained.

Many components of the standard library implement move semantics, allowing to transfer ownership of the assets and properties of an object directly without having to copy them when the argument is an rvalue.

Although note that -in the standard library- moving implies that the moved-from object is left in a valid but unspecified state. Which means that, after such an operation, the value of the moved-from object should only be destroyed or assigned a new value; accessing it otherwise yields an unspecified value.

The function returns the same as:
1
static_cast<remove_reference<decltype(arg)>::type&&>(arg)

Header <algorithm> overloads this function, providing a similar behavior applied to ranges.

Parameters

arg
An object.

Return value

An rvalue reference that refers to arg.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// move example
#include <utility>      // std::move
#include <iostream>     // std::cout
#include <vector>       // std::vector
#include <string>       // std::string

int main () {
  std::string foo = "foo-string";
  std::string bar = "bar-string";
  std::vector<std::string> myvector;

  myvector.push_back (foo);                    // copies
  myvector.push_back (std::move(bar));         // moves

  std::cout << "myvector contains:";
  for (std::string& x:myvector) std::cout << ' ' << x;
  std::cout << '\n';

  return 0;
}

The first call to myvector.push_back copies the value of foo into the vector (foo keeps the value it had before the call).
The second call moves the value of bar into the vector. This transfers its content into the vector (while bar loses its value, and now is in a valid but unspecified state).

Output:
myvector contains: foo-string bar-string


Data races

Calling this function introduces no data races.
Although notice that passing the returned value to functions implementing move semantics generally involves modifying the value or validity of the object.

Exceptions

No-throw guarantee: this function never throws exceptions.

See also