1. 为什么要有对象移动
使用移动而非拷贝对象能够大大提升性能。一些不能被共享的资源类的对象不能拷贝但是可以移动。eg. IO 类 unique_ptr 类
2. 如何做到对象移动
2.1 什么是右值?
“左值持久;右值短暂” 左值有持久的状态,而右值要么是字面值常量,要么是在表达式求值过程中创建的临时对象。
2.2 右值引用
必须绑定到右值的引用。支持移动操作智能绑定到一个将要销毁的对象使用右值引用的代码可以自由地接管所引用的对象资源
int i = 42;int &r = i;//正确,r是i的左值引用int &r2 = i * 42;//错误,i*42是一个右值const int &r3 = i * 42;//正确,可以将一个const的引用绑定到一个右值上int &&rr = i;//错误,不能将一个右值引用绑定到一个左值上int &&rr2 = i * 42; //正确,将rr2绑定到右值上 int &&rr1 = 42; //正确,字面常量是右值int &&r2 = rr1;//错误,表达式rr1是左值
2.3 标准库 move 函数
可通过move 函数用来显式地将一个左值转换为对应的右值引用类型。
#include <utility>int rr3 = std::move(rr1); //正确
2.4 成员函数实现对象移动
如果一个成员函数同时提供拷贝和移动版本,一个版本指向接受一个指向 const 的左值引用,第二个版本接受一个指向非 const 的右值引用。
void push_back(const X&); //拷贝,绑定到任意类型的Xvoid push_back(X&&);//移动,只能绑定到类型X的可修改右值inline void StrVec::push_back(const std::string& s){chk_n_alloc(); // ensure that there is room for another element// construct a copy of s in the element to which first_free pointsalloc.construct(first_free++, s); }inline void StrVec::push_back(std::string &&s) {chk_n_alloc(); // reallocates the StrVec if necessaryalloc.construct(first_free++, std::move(s));}
调用举例:
StrVec vec;string s = "some string or another";vec.push(s);//调用push(const string &)vec.push("done");//调用push(string &&)