Why we use reference return in assignment operator overloading and not at plus-minus ops?

前端 未结 5 598
予麋鹿
予麋鹿 2021-02-01 07:19

As I read in books and in the web, in C++ we can overload the \"plus\" or \"minus\" operators with these prototypes (as member functions of a class Money):

5条回答
  •  天涯浪人
    2021-02-01 07:29

    Returning a reference from assignment allows chaining:

    a = b = c;  // shorter than the equivalent "b = c; a = b;"
    

    (This would also work (in most cases) if the operator returned a copy of the new value, but that's generally less efficient.)

    We can't return a reference from arithmetic operations, since they produce a new value. The only (sensible) way to return a new value is to return it by value.

    Returning a constant value, as your example does, prevents move semantics, so don't do that.

提交回复
热议问题