< cpp‎ | utility
Revision as of 16:54, 1 July 2013 by P12bot (Talk | contribs)

Defined in header <utility>
template< class T >
typename std::remove_reference<T>::type&& move( T&& t );
(since C++11)

std::move obtains an rvalue reference to its argument, which converts it to an xvalue.

Code that receives such an xvalue has the opportunity to optimize away unnecessary overhead by moving data out of the argument, leaving it in a valid but unspecified state.

In detail, code that is passed an rvalue (either a prvalue such as a temporary object or an xvalue such as the one produced by std::move) that identifies a resource-owning object has the option (but isn't required) to move the resource out of the argument in order to run more quickly, leaving the argument with a valid but unspecified value. The library code is required to leave a valid value in the argument, but unless the type or function documents otherwise, there are no other constraints on the resulting argument value. This means that it's generally wisest to avoid using a moved-from argument again. If you have to use it again, be sure to re-initialize it with a known value before doing so.



t - the object to be moved

Return value

static_cast<typename std::remove_reference<T>::type&&>(t)


noexcept specification:  


#include <iostream>
#include <utility>
#include <vector>
#include <string>
int main()
    std::string str = "Hello";
    std::vector<std::string> v;
    // uses the push_back(const T&) overload, which means 
    // we'll incur the cost of copying str
    std::cout << "After copy, str is \"" << str << "\"\n";
    // uses the rvalue reference push_back(T&&) overload, 
    // which means no strings will copied; instead, the contents
    // of str will be moved into the vector.  This is less
    // expensive, but also means str might now be empty.
    std::cout << "After move, str is \"" << str << "\"\n";
    std::cout << "The contents of the vector are \"" << v[0]
                                         << "\", \"" << v[1] << "\"\n";
    // string move assignment operator is often implemented as swap,
    // in this case, the moved-from object is NOT empty
    std::string str2 = "Good-bye";
    std::cout << "Before move from str2, str2 = '" << str2 << "'\n";
    v[0] = std::move(str2);
    std::cout << "After move from str2, str2 = '" << str2 << "'\n";

Possible output:

After copy, str is "Hello"
After move, str is ""
The contents of the vector are "Hello", "Hello"
Before move from str2, str2 = 'Good-bye'
After move from str2, str2 = 'Hello'



See also

forwards a function argument
(function template) [edit]
obtains an rvalue reference if the move constructor does not throw
(function template) [edit]
moves a range of elements to a new location
(function template) [edit]