本文共 1259 字,大约阅读时间需要 4 分钟。
1. 为什么要有对象移动
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 函数用来显式地将一个左值转换为对应的右值引用类型。
#includeint 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 points alloc.construct(first_free++, s); }inline void StrVec::push_back(std::string &&s) { chk_n_alloc(); // reallocates the StrVec if necessary alloc.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 &&)
转载地址:http://gbdz.baihongyu.com/