探讨一下C++11的move函数
在C++11中,标准库在<utility>中提供了一个有用的函数std::move,std::move并不能移动任何东西,
它唯一的功能是将一个左值强制转化为右值引用,继而可以通过右值引用使用该值,以用于移动语义。
从实现上讲,std::move基本等同于一个类型转换:static_cast<T&&>(lvalue);
std::move函数可以以非常简单的方式将左值引用转换为右值引用。
通过std::move,可以避免不必要的拷贝操作。
std::move是为性能而生。
std::move是将对象的状态或者所有权从一个对象转移到另一个对象,只是转移,没有内存的搬迁或者内存拷贝。
#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
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 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.
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";
return 0;
}
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;
ProcessValue(a);
// std::move函数可以以非常简单的方式将左值引用转换为右值引用
ProcessValue(std::move(a));
return 0;
}
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;
}
太强辣!