Returning reference to this object is often used in assignment operator overloading. It is also used as a base for named parameters idiom which allows to initialize object by chain of calls to setter methods: Params().SetX(1).SetY(1)
each of which returns reference to *this.
But is it correct to return reference to *this
. What if we call the method returning reference to this for a temporary object:
#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;
}
auto& ref = MakeObj(5).Me();
. Yes, you can create an lvalue that designates a temporary object this way (which is one reason I often correct people who use the terms "temporary object" and "rvalue" interchangeably) – Stonybroke