练习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的次数逐渐增多的时候,拷贝操作也用更多。