Search code examples
c++constructortemporaryrvalue

Constructed temporary object are lvalue?


Suppose that i have a class named Foo with copy-assignment operators, i thought that this:

Foo() = Foo();

wasn't permitted, because i thought (sorry, again) that Foo() was an rvalue (so i can't assign to it), being a temporary object. Obviously, i tried to make this code work, and it worked properly, displaying some string to verify that my programm correctly uses the copy-assignment operator.

Am I wrong? Or is this a sort of bug? What use can have?


Solution

  • Foo() is an rvalue, that's for sure.

    But the expression Foo() = Foo() is equivalent to Foo().operator=(Foo()). Even though Foo() is an rvalue, you are still allowed to call a member function on it, even a member function that modifies it.

    Of course, an rvalue of fundamental type isn't allowed on the left-hand side of an assignment. Fundamental types are treated differently from user-defined types in this regard.

    This is why, in C++, "lvalue" shouldn't be defined as "something that can appear on the left hand side of an assignment"!