博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
c++ 右值引用
阅读量:2394 次
发布时间:2019-05-10

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

首先,什么是左值、右值?

左值是能出现在等号左边和右边的变量,右值是只能出现在等号右边的变量(或表达式)。

左值引用为 & , 而右值引用为 &&。

那么为什么需要右值引用呢?主要是为了处理c++临时对象的低效的问题,使用右值引用可以减少不必要的拷贝构造。

举个例子:

#include 
using namespace std;class A {public: A(int a) { cout << "constructor" << endl; this->num = new int(a); } A(const A& t) { cout << "copy" << endl; this->num = new int(*(t.num)); } int* num;};A get_A() { A a(10); return a;}int main() { A test = get_A();}

输出结果为:

constructor

copy
copy

调用了两次拷贝构造函数(一次用在临时变量的拷贝,一次用在test的拷贝)。使用g++可能会得到不同的输出,因为g++对此进行了优化,需要使用参数-fno-elide-constructors。

那么我们通过实现多一个函数A(A&& t)来使用右值引用:

class A {public:  A(int a) {    cout << "constructor" << endl;    this->num = new int(a);  }  A(const A& t) {    cout << "copy" << endl;    this->num = new int(*(t.num));  }  A(A&& t) {    cout << "move" << endl;;    this->num = t.num;  }  int* num;};A get_A() {  A a(10);  return a;}int main() {  A test = get_A();}

输出结果为:

constructor

move
move

可以看到,使用右值引用,避免了不必要的拷贝构造,而只是将资源(此处为num变量)的归属做了调整。

另外,我们还可以使用std::move()函数将左值变为右值来避免拷贝构造。

class A {public:  A(int a) {    cout << "constructor" << endl;    this->num = new int(a);  }  A(const A& t) {    cout << "copy" << endl;    this->num = new int(*(t.num));  }  A(A&& t) {    cout << "move" << endl;;    this->num = t.num;  }  int* num;};A get_A() {  A a(10);  return a;}int main() {  A test(10);  A b(test);  A c(std::move(test));}

输出结果为:

constructor

copy
move

转载地址:http://twwob.baihongyu.com/

你可能感兴趣的文章
Spring的核心中IOC、DI
查看>>
Spring中注解的使用
查看>>
Spring的认识
查看>>
maven项目出现如下错误,求指点;CoreException: Could not calculate build plan:
查看>>
理解Paxos算法的证明过程
查看>>
详解 JVM Garbage First(G1) 垃圾收集器
查看>>
Java 8 函数式编程入门之Lambda
查看>>
用高阶函数轻松实现Java对象的深度遍历
查看>>
WindowsApi+Easyx图形库的透明时钟
查看>>
Eclipse LUNA配置TomCat(非j2ee版本)
查看>>
树莓派安装mysql-srver报错 404 not found!
查看>>
Ubuntu 14.04LTS 下安装.net框架
查看>>
Eclipse 配置Groovy语言环境 && Java工程运行Groovy
查看>>
人工智能术语表
查看>>
Tensorflow Python API 翻译(sparse_ops)
查看>>
Tensorflow Python API 翻译(math_ops)(第一部分)
查看>>
Tensorflow Python API 翻译(math_ops)(第二部分)
查看>>
Tensorflow Python API 翻译(constant_op)
查看>>
利用 TensorFlow 入门 Word2Vec
查看>>
多任务学习与深度学习
查看>>