To my knowledge, returning *this is the norm of writing overloaded operator=. But this may promote a rvalue to a lvalue!
struct Foo {
Foo& operator=(const Foo &t) { return *this; }
};
int main() {
const Foo &ref = Foo();
//Foo &ref1 = Foo(); // This line won't compile.
//But the following line compiles. Isn't it dangerous?
//Also please note that if = is not overloaded, the synthesized operator= will NOT let it compile.
Foo &ref2 = (Foo() = Foo());
return 0;
}
You’re right. The short answer is that this is legal, but is dangerous for the reasons you point out.
Another (similar) example was added to C++11, as part of the standard no less, with the rvalue stream output, which returns an lvalue reference.
So
std::ostream& s = std::ofstream("foo.txt") << "Oh boy";is legal, but creates a dangling reference.I believe that C++11 compilers will allow member functions to be restricted to the case when the object is an lvalue, which should allow you to prevent the problem at all. The below will only allow the assignment when
*thisis an lvalue, so it prevents you from converting by accident.