分配给rvalue:为什么要编译?

For*_*ent 5 c++ reference rvalue lvalue

在以下示例中:

class A {
  private: double content;

  public:
  A():content(0) {}

  A operator+(const A& other) {     
    content += other.content;
    return *this;
  }

 void operator=(const A& other) {
       content = other.content;
  }

};
Run Code Online (Sandbox Code Playgroud)

A是一个double的简单包装器,+并且=运算符已经过载.在以下用途中:

 int main(int argc, char *argv[]) {
    A a, b, c;
    (a+b) = c ; // Why is this operation legal?
}
Run Code Online (Sandbox Code Playgroud)

为什么(a+b) = c编译?我想知道为什么这个陈述是合法的,因为结果(a+b)必须是一个rvalue.我没有从中返回参考operator+.

Tar*_*ama 12

(a+b) = c是一样的(a+b).operator=(c).赋值运算符中的rvalue引用没有特殊规则,它只遵循通常的函数调用规则.如果要阻止使用rvalues调用,可以添加ref-qualifier:

void operator= (const A& other) & {
//                              ^
     content = other.content;
}
Run Code Online (Sandbox Code Playgroud)

这将只允许在左值上调用该函数.