分配给右值:为什么要编译?

assigning to rvalue: why does this compile?

在下面的例子中:

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;
  }

};

A 是 double 的简单包装器,其中 += 运算符已被重载。在下面使用:

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

为什么(a+b) = c可以编译?我想知道为什么这个语句是合法的,因为(a+b)的结果一定是一个rvalue.我不会从 operator+.

返回参考

(a+b) = c 等同于 (a+b).operator=(c)。赋值运算符中的右值引用没有特殊规则,它只是遵循通常的函数调用规则。如果你想防止调用右值,你可以添加一个 ref-qualifier:

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

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