c++c++11language-lawyerrvaluelvalue-to-rvalue

Why is it possible to assign to an rvalue of class type?


Why is this code compiling? I thought that rvalues returned by the constructor are not located in memory and therefore can't be used as lvalues.

class Y {
public :
    explicit Y(size_t num = 0) {}
};

int main() {
    Y(1) = Y(0); // WHAT?!?
    return 0;
}

Solution

  • The synthesized assignment operator is declared as one of these (if it can be synthesized and isn't declared as deleted) according to see 12.8 [class.copy] paragraph 18:

    That is, like for any other member function which isn't specifically declared with ref-qualifiers it is applicable to rvalues.

    If you want to prevent a temporary object on the left hand side of the assignment you'd need to declare it correspondingly:

    class Y {
    public :
        explicit Y(std::size_t num = 0);
        Y& operator= (Y const&) & = default;
    };
    

    The standard uses the name ref-qualifier for the & before the = default. The relevant proposal is N2439. I don't know where there is a good description of ref-qualifiers. There is some information at this question.