Home > Backend Development > C++ > body text

Assignment to Rvalues: Forbidden or Feature? Why Can We Assign to a Return Value?

Patricia Arquette
Release: 2024-10-31 09:19:30
Original
400 people have browsed it

 Assignment to Rvalues: Forbidden or Feature? Why Can We Assign to a Return Value?

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;
}
Copy after login

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:

  • Y& operator=(Y const&)
  • Y& operator=(Y&)()

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;
};
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!