返回对该对象的引用通常用于赋值运算符重载。它还用作命名参数习惯用法的基础,它允许通过调用 setter 方法链来初始化对象:Params().SetX(1).SetY(1)
每个方法都返回对 *this 的引用。
但是返回对*this
. 如果我们为临时对象调用返回对 this 的引用的方法会怎样:
#include <iostream>
class Obj
{
public:
Obj(int n): member(n) {}
Obj& Me() { return *this; }
int member;
};
Obj MakeObj(int n)
{
return Obj(n);
}
int main()
{
// Are the following constructions are correct:
std::cout << MakeObj(1).Me().member << std::endl;
std::cout << Obj(2).Me().member << std::endl;
Obj(3).Me() = Obj(4);
return 0;
}