分配给右值:为什么要编译? [英] 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的简单包装器,其 +
和 =
运算符已被重载.在以下用途中:
A
is a simple wrapper for a double for which the +
and =
operators have been overloaded. In the following use:
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 +
返回参考.
Why does (a+b) = c
compile? I would like to know why this statement is legal, because the result of (a+b)
must be an rvalue
. I am not returning a reference from operator+
.
推荐答案
(a + b)= c
与(a + b).operator =(c)
.赋值运算符中的右值引用没有特殊的规则,只是遵循通常的函数调用规则.如果要防止使用右值调用,可以添加一个ref-qualifier:
(a+b) = c
is the same as (a+b).operator=(c)
. There is no special rule for rvalue references in assignment operators, it just follows usual function call rules. If you want to prevent calling with rvalues, you can add a ref-qualifier:
void operator= (const A& other) & {
// ^
content = other.content;
}
这将仅允许在左值上调用该函数.
This will only allow the function to be called on lvalues.
这篇关于分配给右值:为什么要编译?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!