rvalue on the left side

a 夏天 提交于 2019-11-29 18:54:32

问题


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

#include <iostream>
#include <vector>

class Y {
public :
    explicit Y(size_t num = 0)
    : m_resource {std::vector<int>(num)}
    {
    }

    std::vector<int> m_resource;
};

int main(int argc, const char * argv[]) {
    Y(1) = Y(0); // WHAT?!?
    return 0;
}

回答1:


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:

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

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.




回答2:


Not sure where you got that specific rule of thumb. If any, a rule of thumb would be (from Scott Meyers): if it has a name, it's an lvalue.

In this case, you're creating a temporary object and passing it to an assignment method/function. There is no problem with that. In fact, it might even make sense to do so, as in

// Applies foo to a copy, not the original.
(Y(1) = y).foo()

It is true that Y(*) don't have names here, though, and hence they are rvalues.



来源:https://stackoverflow.com/questions/34835686/rvalue-on-the-left-side

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!