Assignment to Rvalue: Why and How?
Why is it possible to assign to a return value (rvalue) of a class type? Conventionally, rvalues are considered ephemeral, lacking a memory address. How, then, can they be used as left-hand values (lvalues)?
Consider the following puzzling code:
class Y { public : explicit Y(size_t num = 0) {} }; int main() { Y(1) = Y(0); // WHAT?!? return 0; }
This code compiles without errors, although it might seem illogical. To understand why, we need to delve into the mechanics behind assignment operators.
Synthesized Assignment Operators
When a class does not explicitly define an assignment operator, the compiler automatically generates one. The synthesized operator can take one of two forms:
The latter form is notable because it applies to rvalues. Hence, in the example above, the compiler generates an assignment operator that can accept the rvalue returned by the constructor Y(1).
Preventing Assignment to Rvalues
If you wish to prohibit assignment to rvalues, you can explicitly declare the assignment operator with ref-qualifiers. In this way, you can restrict the operator to only accept lvalues. For instance:
class Y { public : explicit Y(std::size_t num = 0); Y& operator=(Y const&) & = default; };
By using the ref-qualifier &, you ensure that the synthesized assignment operator is only available for lvalues.
The above is the detailed content of Assignment to Rvalues: Forbidden or Feature? Why Can We Assign to a Return Value?. For more information, please follow other related articles on the PHP Chinese website!