Home > Article > Backend Development > Can You Assign to Rvalue References of Class Type? A Paradox Explained.
Assigning to Rvalue References of Class Type: A Paradox Resolved
In the realm of C , the distinction between lvalues and rvalues is paramount. Lvalues represent objects with memory locations that can be modified, while rvalues embody temporary objects or constants that cannot. However, an intriguing code snippet raises questions about this fundamental divide:
<code class="cpp">class Y { public: explicit Y(size_t num = 0) {} }; int main() { Y(1) = Y(0); // Here lies the enigma! return 0; }</code>
Why does this code compile? Isn't the rvalue returned by the constructor ephemeral and thus unfit for assignment?
The key to understanding this paradox lies in the implicit assignment operator in C . When the assignment operator is not explicitly defined for a class, the compiler synthesizes a default assignment operator. Crucially, this synthesized operator can be applicable to rvalues in some cases.
This is where the explicit keyword plays a role. In the given example, the Y class does not declare an assignment operator, so the compiler generates one. The explicit keyword prevents implicit conversions from rvalues, but it does not prevent the synthesized assignment operator from being applicable to rvalues.
Thus, in our code, the synthesized assignment operator:
<code class="cpp">Y& Y::operator=(Y const&);</code>
or
<code class="cpp">Y& Y::operator=(Y&);</code>
can be invoked with the rvalue Y(1) on the left-hand side. This allows the assignment to proceed, even though Y(1) is an rvalue.
To prevent assignment to temporary objects, one can explicitly declare the assignment operator with a ref-qualifier (&):
<code class="cpp">class Y { public: explicit Y(std::size_t num = 0); Y& operator=(Y const&) & = default; };</code>
In this case, the assignment operator will not be synthesized, and attempting to assign to an rvalue will result in a compilation error.
The above is the detailed content of Can You Assign to Rvalue References of Class Type? A Paradox Explained.. For more information, please follow other related articles on the PHP Chinese website!