Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are the postfix operators designed to return-by-value?

In particular, the prefix operators' return-by-reference makes sense to me - it's useful, in case one wants to do further operations on the object.

However, I can't get my head around why the postfix operator was designed to return by value.

Is it solely a convention, or was there a good reason why it was designed this way (like a return-by-value does not make sense for postfix, but makes sense for prefix)?

Can someone explain?

ANSWER

Thanks to the answers below, it appears that the postfix operator doesn't necessarily have to return by value (according to the standards).

However, due to the semantic requirements of the postfix operator (return the original value, but increment the reference to the original value afterwards), in conjunction with the standard requirement of:

Operator overloads are functions, and thus all side effects must take place before the function completes.

as explained clearly by David Rodriguez below, bifurcating the value seems to be a necessary consequence of the semantic requirements.

In this context, since we are returning the other value (not the original reference, since it will have changed by the closing brace of the function), returning the other value by-value seems to make the most sense.

like image 844
kfmfe04 Avatar asked Feb 12 '13 04:02

kfmfe04


1 Answers

Postfix operators are expressions that yield the original value and then modify the object. At the same time, operator overloads are functions, and thus all side effects must take place before the function completes. The only way of attaining the required semantics is by copying the initial state of the object before applying the change. The original state must be returned by value (if a reference was returned, the evaluation of the expression would yield the state of the object after the function completes, and thus would have the semantics of prefix operators, not postfix ones)

like image 99
David Rodríguez - dribeas Avatar answered Oct 20 '22 20:10

David Rodríguez - dribeas