C++知识点-RvalueReference03

这篇博文介绍右值的概念。看一下下边的代码

void printInt(int& i){cout<<"lvalue reference: "<<i<<endl;}
void printInt(int&& i){cout<<"rvalue reference: "<<i<<endl;}

int main(){
    //What is rvalue reference?
    int a = 5;  // a is a lvalue
    printInt(a);    //Call printInt(int& i)
    pirntInt(6);    //Call PrintInt(int&& i)
}

上面代码第8行就是右值引用的例子。下边的代码进一步讲解的这个概念。

#include <iostream>

using namespace std;

class boVector {
	int size;
	double* arr_;
public:
	boVector(const boVector& rhs) { // Copy constructor
		size = rhs.size;
		arr_ = new double[size];
		for (int i = 0; i < size; i++) { arr_[i] = rhs.arr_[i]; }
		cout << "copy constructor " << endl;
	}
	boVector(boVector&& rhs) { // Move constructor
		size = rhs.size;
		arr_ = rhs.arr_;
		rhs.arr_ = nullptr;
		cout << "move constructor " << endl;
	}
	boVector() = default;
	~boVector() { delete arr_; }
};

void foo(boVector v)
{
	cout << "foo " << endl;
}

void foo_ref(boVector &v)
{
	cout << "foo_ref " << endl;
}

boVector createBoVector() {//Creates a boVector
	return boVector();
}

int main() {
	boVector reusable = createBoVector();
	foo(reusable);					//是个左值,调用copy construct
	foo(createBoVector());			//不调用任何constrcut
	foo(std::move(reusable));		//是个右值,调用deep construct
	boVector reusable1 = createBoVector();
	foo_ref(reusable);			    //引用,不调用构造函数
		
	return 0;
}

 

最后的话:

这篇文章发布在CSDN/蓝色的杯子, 没事多留言,让我们一起爱智求真吧.我的邮箱wisdomfriend@126.com

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值