C ++为什么赋值运算符应该返回一个const引用以避免(a = b)= c [英] C++ why the assignment operator should return a const ref in order to avoid (a=b)=c

查看:313
本文介绍了C ++为什么赋值运算符应该返回一个const引用以避免(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) $ c> x.operator =(y),它返回对象 x 。因此,(x = y)= z 表示(x.operator =(y))operator =(z)。括号中的表达式设置 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引用以避免(a = b)= c的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆