C++ why the assignment operator should return a const ref in order to avoid (a=b)=c

后端 未结 5 1430
情书的邮戳
情书的邮戳 2020-11-30 04:16

I am reading a book about C++ and more precisely about the operator overloading.

The example is the following:

const Array &Array::operator=(cons         


        
5条回答
  •  一整个雨季
    2020-11-30 04:29

    (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.

    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.

提交回复
热议问题