C 11中std::move的使用


std::move is used to indicate that an object t may be “moved from”, i.e. allowing the efficient transfer of resources from t to another object. In particular,std::move produces an xvalue expression that identifies its argument t. It is exactly equivalent to a static_cast to an rvalue reference type.

In C 11, in addition to copy constructors, objects can have move constructors. (And in addition to copy assignment operators, they have move assignment operators.) The move constructor is used instead of the copy constructor, if the object has type “rvalue-reference” (Type &&). std::move() is a cast that produces an rvalue-reference to an object, to enable moving from it.

It’s a new C way to avoid copies. For example, using a move constructor, a std::vector could just copy its internal pointer to data to the new object, leaving the moved object in an incorrect state, avoiding to copy all data.

在C 11中,標準庫在<utility>中提供了一個有用的函式std::move,std::move並不能移動任何東西,它唯一的功能是將一個左值強制轉化為右值引用,繼而可以通過右值引用使用該值,以用於移動語義。從實現上講,std::move基本等同於一個型別轉換:static_cast<T&&>(lvalue);






#include "move.hpp"
#include <iostream>
#include <utility>
#include <vector>
#include <string>
// reference: http://en.cppreference.com/w/cpp/utility/move
int test_move1()
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 be 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";
return 0;
// reference: http://www.ibm.com/developerworks/cn/aix/library/1307_lisl_c11/
void ProcessValue(int& i)
std::cout << "LValue processed: " << i << std::endl;
void ProcessValue(int&& i)
std::cout << "RValue processed: " << i << std::endl;
int test_move2()
int a = 0;
// std::move函式可以以非常簡單的方式將左值引用轉換為右值引用
return 0;
// reference: http://www.cplusplus.com/reference/utility/move/
int test_move3()
std::string foo = "foo-string";
std::string bar = "bar-string";
std::vector<std::string> myvector;
// 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)
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;