Namespaces
Variants
Views
Actions

std::move

From cppreference.com
< cpp‎ | utility
Revision as of 06:11, 17 April 2013 by Cubbi (Talk | contribs)

Template:ddcl list begin <tr class="t-dsc-header">

<td>
Defined in header <utility>
</td>

<td></td> <td></td> <tr class="t-dcl ">

<td >
template< class T >
typename std::remove_reference<T>::type&& move( T&& t );
</td>

<td class="t-dcl-nopad"> </td> <td > (since C++11) </td> </tr> Template:ddcl list end

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

Library code that's passed an rvalue (either prvalue such as a temporary object or 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 an empty 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.

Contents

Parameters

t - the object to be moved

Return value

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

Exceptions

noexcept specification:  
noexcept
  

Example

#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
    v.push_back(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.
    v.push_back(std::move(str));
    std::cout << "After move, str is \"" << str << "\"\n";
 
    std::cout << "The contents of the vector are \"" << v[0]
                                         << "\", \"" << v[1] << "\"\n";
}

Output:

After copy, str is "Hello"
After move, str is ""
The contents of the vector are "Hello", "Hello"

Complexity

Constant

See also

Template:cpp/algorithm/dcl list move
(C++11)
forwards a function argument
(function template) [edit]
obtains an rvalue reference if the move constructor does not throw
(function template) [edit]