return value of operator overloading in C++


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 underneath rule of that? Especially at the case when you can use the operator continuously, such as cout<<x<<y.

For example, when implementing a + operation "string + (string)". how would you return the return value, by ref or by val.

share improve this question
 

5 Answers

up vote 33 down vote accepted

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

share improve this answer
 
6 
Which goes hand in hand with "if it's const, return a value, if it's non-const, return a reference". –   GManNickG Feb 25 '10 at 20:11
6 
Technically << does not modify the existing value. It's just a left-shift operator. It's the stream interface breaking the rules. –   kennytm  Feb 25 '10 at 20:13
 
@GMan correct, although that doesn't cover the cases (such as operator<<) where the overload is implemented as a non-member. –   Tyler McHenry  Feb 25 '10 at 20:13
1 
The "produces a new value" is a little imprecise. ++ produces a new value, after all. How about keep the second half of the sentence, and add "All other values should return by value." –   thebretness  Feb 25 '10 at 20:14
2 
@KennyTM I had no idea old C codgers were still putting up that fight after so many years. :) –  Tyler McHenry  Feb 25 '10 at 20:17

To attempt an answer to your question regarding strings, the operator+() for strings is almost always implemented as a free (non-member) function so that implicit conversions can be performed on either parameter. That is so you can say things like:

string s1 = "bar";
string s2 = "foo" + s1;

Given that, and that we can see that neither parameter can be changed, it must be declared as:

RETURN_TYPE operator +( const string & a, const string & b );

We ignore the RETURN_TYPE for the moment. As we cannot return either parameter (because we can't change them), the implementation must create a new, concatenated value:

RETURN_TYPE operator +( const string & a, const string & b ) {
    string newval = a;
    newval += b;    // a common implementation
    return newval;
}

Now if we make RETURN_TYPE a reference, we will be returning a reference to a local object, which is a well-known no-no as the local object don't exist outside the function. So our only choice is to return a value, i.e. a copy:

string operator +( const string & a, const string & b ) {
    string newval = a;
    newval += b;    // a common implementation
    return newval;
}
share improve this answer
 
 
So, for freeing the allocated result, am I correct that because the invocation of the Operator is in effect a declaration, the anonymous return value goes on the stack, and so is freed when the containing function returns? –   no comprende  Jul 14 at 14:51

If you want your operator overload to behave like the built-in operator, then the rule is pretty simple; the standard defines exactly how the built-in operators behave and will indicate if the result of a built-in is an rvalue or an lvalue.

The rule you should use is:

  • if the built-in operator returns an rvalue then your overload should return a reference
  • if the built-in returns an lvalue then your overload should return a value

However, your overload isn't required to return the same kind of result as the built-in, though that's what you should do unless you have a good reason to do otherwise.

For example, KennyTM noted in a comment to another answer that the stream overloads for the <<and >> operators return a reference to the left operand, which is not how the built-ins work. But the designers of the stream interface did this so stream I/O could be chained.

share improve this answer
 
 
For reference the built-in operators are in § 13.6 of the N3337 draft C++11 standard, which is the only version of the standard I have at hand. –   Mark Ransom  Jul 27 '12 at 17:25

Depending on the operator you may have to return by value.

When both can be used though, like in operator+= you could consider the following:

  • If your objects are immutable it's probably better to return by value.
  • If your objects are mutable it's probably better to return by reference.
share improve this answer
 

Usually you return by reference in an operation that changes the value of the things it's operating on, like = or +=. All other operations are return by value.

This is more a rule of thumb, though. You can design your operator either way.

share improve this answer
1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值