为什么将后缀运算符设计为按值返回? [英] Why are the postfix operators designed to return-by-value?

查看:73
本文介绍了为什么将后缀运算符设计为按值返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

特别是,前缀运算符的按引用返回对我来说很有意义-如果有人想对该对象做进一步的操作,这很有用.

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.

但是,我无法理解为何将postfix运算符设计为按值返回的原因.

这仅仅是约定,还是有充分的理由说明采用这种方式进行设计(例如按值返回对于后缀而言没有意义,而对于前缀而言则有意义)?

有人可以解释吗?

答案

由于下面的回答,看来后缀运算符不一定 必须按值返回(根据标准).

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:

运算符重载是函数,因此所有副作用都必须在函数完成之前发生.

正如下面的 David Rodriguez 明确解释的那样,分叉价值似乎是必要的语义要求的结果.

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

在这种情况下,由于我们要返回另一个值(不是原始引用,因为它将被函数的右花括号更改),因此返回另一个值 by-value 似乎是最有意义.

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.

推荐答案

后缀运算符是产生原始值然后修改对象的表达式.同时,操作员重载是函数,因此所有副作用都必须在函数完成之前发生.获得所需语义的唯一方法是在应用更改之前复制对象的初始状态.原始状态必须按值返回(如果返回了引用,则对表达式的求值将在函数完成后产生对象的状态,因此具有前缀运算符的语义,而不是后缀运算符的语义)

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)

这篇关于为什么将后缀运算符设计为按值返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆