How to avoid overloaded assignment operator turning rvalue to lvalue?

Viewed 472

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;
}
2 Answers
Related