博客
关于我
C++ Primer 5th笔记(chap 13 拷贝控制) 对象移动
阅读量:83 次
发布时间:2019-02-26

本文共 1259 字,大约阅读时间需要 4 分钟。

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 
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 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/

你可能感兴趣的文章
MySQL binlog三种模式
查看>>
multi-angle cosine and sines
查看>>
Mysql Can't connect to MySQL server
查看>>
mysql case when 乱码_Mysql CASE WHEN 用法
查看>>
Multicast1
查看>>
mysql client library_MySQL数据库之zabbix3.x安装出现“configure: error: Not found mysqlclient library”的解决办法...
查看>>
MySQL Cluster 7.0.36 发布
查看>>
Multimodal Unsupervised Image-to-Image Translation多通道无监督图像翻译
查看>>
MySQL Cluster与MGR集群实战
查看>>
multipart/form-data与application/octet-stream的区别、application/x-www-form-urlencoded
查看>>
mysql cmake 报错,MySQL云服务器应用及cmake报错解决办法
查看>>
Multiple websites on single instance of IIS
查看>>
mysql CONCAT()函数拼接有NULL
查看>>
multiprocessing.Manager 嵌套共享对象不适用于队列
查看>>
multiprocessing.pool.map 和带有两个参数的函数
查看>>
MYSQL CONCAT函数
查看>>
multiprocessing.Pool:map_async 和 imap 有什么区别?
查看>>
MySQL Connector/Net 句柄泄露
查看>>
multiprocessor(中)
查看>>
mysql CPU使用率过高的一次处理经历
查看>>