Why does overloaded assignment operator return reference to class?

后端 未结 3 394
一生所求
一生所求 2021-01-18 17:40
class item {
public:
    item& operator=(const item &rh) {
        ...
        ...
        return *this;
    }
};

Is the following signatur

相关标签:
3条回答
  • 2021-01-18 17:51

    The signature with void would not allow chained assignments:

    a = b = c;
    

    (Look at Johannes' answer for one more example of a usage pattern based on assignment returning the assigned value.)

    That's why using such signatures is discouraged. However, if I am not mistaken, you actually can use such a signature.

    0 讨论(0)
  • 2021-01-18 18:04

    It is not "wrong", but surprising. An assignment evaluates to the target object. That's what the builtin meaning is. If you define it different for your own class, people could become confused.

    Example:

    int c;
    while((c = getchar()) != EOF) {
      // ...
    }
    

    The assignment to c returned c itself and compared it to EOF afterwards. Users would expect your item class to behave similar.

    0 讨论(0)
  • 2021-01-18 18:06

    It's perfectly legal. But when you declare operator= like that, you will be unable to make "chain of assignment":

    item a(X);
    item b;
    item c;
    c = b = a;
    

    Reference allows modifying returned value. Since operator= is evaluated from right to left, the usage I showed to you is working.

    EDIT Also, as others mentioned, return value is often used in expressions like while (a = cin.get()) != 'q'). But you also can declare operator like A operator=(const A&) (returns copy) or const A& operator(const A&) (returns const reference). My point is: this operator can return anything, but the idiomatic way is to return non-const reference to itself.

    0 讨论(0)
提交回复
热议问题