习题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();
}