return value of operator overloading in C++

前端 未结 5 2096
逝去的感伤
逝去的感伤 2020-11-29 18:19

I have a question about the return value of operator overloading in C++. Generally, I found two cases, one is return-by-value, and one is return-by-reference. So what\'s the

5条回答
  •  眼角桃花
    2020-11-29 18:54

    Some operators return by value, some by reference. In general, an operator whose result is a new value (such as +, -, etc) must return the new value by value, and an operator whose result is an existing value, but modified (such as <<, >>, +=, -=, etc), should return a reference to the modified value.

    For example, cout is a std::ostream, and inserting data into the stream is a modifying operation, so to implement the << operator to insert into an ostream, the operator is defined like this:

    std::ostream& operator<< (std::ostream& lhs, const MyType& rhs)
    {
      // Do whatever to put the contents of the rhs object into the lhs stream
      return lhs;
    }
    

    This way, when you have a compound statement like cout << x << y, the sub-expression cout << x is evaluated first, and then the expression [result of cout << x ] << y is evaluated. Since the operator << on x returns a reference to cout, the expression [result of cout << x ] << y is equivalent to cout << y, as expected.

    Conversely, for "string + string", the result is a new string (both original strings are unchanged), so it must return by value (otherwise you would be returning a reference to a temporary, which is undefined behavior).

提交回复
热议问题