第十三章 习题13-51-习题13-60

习题13-51

局部对象意味着要销毁了,这里执行的是移动而不是拷贝;

习题13-52

hp=hp2,

hp2是一个变量,左值。传递给赋值运算符是用拷贝构造,rhs是hp2的副本。赋值完毕后,生成独立的变量,但内容相同;

hp=std::move(hp2),移动构造。rhs.ps指向hp.ps原来的string,hp.ps设置为空指针。交换完毕后,rhs被销毁。hp指向hp2原来的string,hp2为空;

习题13-53

使用了临时变量rhs,执行拷贝构造或移动构造函数,没有必要;

HasPtr &HasPtr::operator=(HasPtr &&rhs)noexcept
{
	if (this != rhs)
	{
		delete ps;
		ps = rhs.ps;
		rhs.ps = nullptr;
		rhs.i = 0;
	}
	return *this;
}

习题13-54

会报错,产生二义性。对于hp=std::move(hp2)赋值语句,两个运算符都会被匹配;

习题13-55

	void push_back(string &&t) { data->push_back(std::move(t)); }

习题13-56

ret由于是变量,是左值,调用左值引用版本的sorted,即本例中的函数,这样会导致循环递归;

习题13-57

正确,Foo(*this)产生一个右值。调用右值版本;

习题13-58

对于56题,是不断重复“左值引用”,无限循环;对于57题,是右值引用,然后左值引用,再调用右值引用;

#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
class Foo {
public:
	Foo sorted() && ;
	Foo sorted() const&;

private:
	vector<int> data;
};

Foo Foo::sorted() &&
{
	sort(data.begin(), data.end());
	cout << "右值引用" << endl; // debug
	return *this;
}

Foo Foo::sorted() const &
{

	cout << "左值引用" << endl;

	    Foo ret(*this);
	    ret.sorted();     // 习题13-56
	    return ret;

	//return Foo(*this).sorted();   //习题13-57
}

int main()
{
	Foo().sorted();
	Foo f;
	f.sorted();
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值