第十三章 13.6.1节练习

练习13.45

解释右值引用和左值引用的区别。

解答:

左值引用就是常规引用。

右值引用是在C++11之后添加到C++的新特性。

【引用】对于常规引用,我们不能将其绑定到要求转换的表达式、字面常量或是返回右值的表达式。

【引用】右值引用有着完全相反的绑定特性:我们可以讲一个右值引用绑定到这类表达式上,但是不能讲一个右值引用直接绑定到一个左值上。


练习13.46

什么类型的引用可以绑定到下面的初始化器上?

int f();
vector<int> vi(100);
int? r1 = f();
int? r2 = vi[0];
int? r3 = r1;
int? r4 = vi[0] * f();
解答:

	vector<int> vi(100);
	int && r1 = f();
	int & r2 = vi[0];
	int & r3 = r1;
	int && r4 = vi[0] * f();

练习13.47:


练习13.48

定义一个vector<String>并在其上多次调用push_back。运行你的程序,查看String被拷贝了多少次。

解答:

没有必要用完整的String定义来做这道题

#include <vector>
#include <iostream>
#include <string>

using namespace std;

class String{
public:
	String() :str(string()){}
	String(const char* cstr) :str(cstr){}
	String(const String& ori) : str(ori.str){ cout << "copy constructor function" << endl; }

	string str;
};
int main(){
	vector<String> test;
	test.push_back("haha0");
	test.push_back("haha1");
	test.push_back("haha2");
	test.push_back("haha3");
	test.push_back("haha4");
}

运行后可以看出,在push_back的次数逐渐增多的时候,拷贝操作也用更多。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值