C++ 为什么赋值运算符应该返回一个 const ref 以避免 (a=b)=c [英] C++ why the assignment operator should return a const ref in order to avoid (a=b)=c
问题描述
我正在阅读一本关于 C++ 的书,更准确地说是关于运算符重载的书.
I am reading a book about C++ and more precisely about the operator overloading.
示例如下:
const Array &Array::operator=(const Array &right)
{
// check self-assignment
// if not self- assignment do the copying
return *this; //enables x=y=z
}
书中关于返回const ref而不是ref的解释是为了避免诸如(x=y)=z之类的赋值.我不明白为什么我们应该避免这种情况.我知道 x=y 在这个例子中首先被评估,因为它返回一个 const 引用,=z 部分不能被执行.但为什么?
The explanation provided by the book about returning const ref instead of ref is to avoid assignments such as (x=y)=z. I don't understand why we should avoid this. I understand that x=y is evaluated first in this example and since it returns a const reference the =z part cannot be executed. But why?
推荐答案
(x=y)
的意思是x.operator=(y)
,返回对象<代码>x.因此,(x=y)=z
的意思是 (x.operator=(y)).operator=(z)
.parens中的表达式将x
设置为y
并返回x
,然后外位将x
设置为z
.它不会像您期望的那样将 y
设置为 z
,而表达式 x = y = z
也是如此.
(x=y)
means x.operator=(y)
, which returns the object x
. Therefore, (x=y)=z
means (x.operator=(y)).operator=(z)
. The expression in parens sets x
to y
and returns x
, and then the outer bit sets x
to z
. It does not set y
to z
as you might expect, and as the expression x = y = z
does.
这种行为是违反直觉的(它们在赋值后应该都相等,对吗?);返回一个 const 引用使它不可能并避免了这个问题.
This behavior is counter-intuitive (they should all be equal after the assignment, right?); returning a const reference makes it impossible and avoids the problem.
这篇关于C++ 为什么赋值运算符应该返回一个 const ref 以避免 (a=b)=c的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!