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:
class Y {
public:
explicit Y(size_t num = 0) {}
};
int main() {
Y(1) = Y(0); // Here lies the enigma!
return 0;
}
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:
Y& Y::operator=(Y const&);
or
Y& Y::operator=(Y&);
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 (&):
class Y {
public:
explicit Y(std::size_t num = 0);
Y& operator=(Y const&) & = default;
};
In this case, the assignment operator will not be synthesized, and attempting to assign to an rvalue will result in a compilation error.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3