重载逗号运算符*真的*会影响其操作数的求值顺序吗?
逗号运算符保证从左到右的计算顺序。
[n3290: 5.18/1]
:逗号运算符从左到右分组。表达式: 赋值表达式 表达式,赋值表达式
一对用逗号分隔的表达式从左到右计算; 左边的表达式是一个被丢弃的值表达式(第 5 条)。 每个 与左侧表达式相关的值计算和副作用 在每个值计算和相关副作用之前排序 使用正确的表达式。结果的类型和值是 右操作数的类型和值;结果具有相同的值 类别作为其右操作数,如果其右操作数则为位字段 是一个左值和一个位域。
关于运算符的唯一其他条款没有提及评估顺序。因此,当运算符重载时,情况仍然如此。
但是,更进一步,在有关表达式的一般性演讲中,当然指出当您重载运算符时规则会发生变化:
[n3290: 5/2]:
[ 注意: 运算符可以重载,即给定 应用于类类型表达式时的含义(第 9 条)或 枚举类型(7.2)。重载运算符的用途发生了变化 进入函数调用,如 13.5 中所述。 重载运算符服从 第 5 条中规定的语法规则,但要求 操作数类型、值类别和求值顺序被替换为 函数调用规则。 运算符之间的关系,例如++a
意思是a+=1
,不保证重载运算符(13.5),并且 不保证 bool 类型的操作数。 —尾注]
但是,这是非规范文本。是否有任何规范性文本定义此规则,或者兼容的编译器可以忽略它?
The comma operator guarantees left-to-right evaluation order.
[n3290: 5.18/1]
: The comma operator groups left-to-right.expression: assignment-expression expression , assignment-expression
A pair of expressions separated by a comma is evaluated left-to-right;
the left expression is a discarded value expression (Clause 5). Every
value computation and side effect associated with the left expression
is sequenced before every value computation and side effect associated
with the right expression. The type and value of the result are the
type and value of the right operand; the result is of the same value
category as its right operand, and is a bit-field if its right operand
is a glvalue and a bit-field.
The only other clause regarding the operator doesn't mention evaluation order. So it would appear that this is still the case when the operator has been overloaded.
But then, further up, in the general spiel regarding expressions, of course it is stated that the rules change when you overload operators:
[n3290: 5/2]:
[ Note: Operators can be overloaded, that is, given
meaning when applied to expressions of class type (Clause 9) or
enumeration type (7.2). Uses of overloaded operators are transformed
into function calls as described in 13.5. Overloaded operators obey
the rules for syntax specified in Clause 5, but the requirements of
operand type, value category, and evaluation order are replaced by the
rules for function call. Relations between operators, such as++a
meaninga+=1
, are not guaranteed for overloaded operators (13.5), and
are not guaranteed for operands of typebool
. —end note ]
However, this is non-normative text. Is there any normative text defining this rule, or could a compliant compiler ignore it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我手头只有 03 标准,但其中 5/3 说“第 5 条定义了运算符应用于尚未重载的类型时的效果”。
因此,第 5 条的所有内容(包括 5.18/1)仅适用于内置运算符,不适用于任何重载函数。
(不过,兼容的编译器始终可以将操作数计算为从左到右重载的
运算符,()
。)I only have the 03 standard to hand, but in it 5/3 says "Clause 5 defines the effects of operators when applied to types for which they have not been overloaded."
So all of clause 5, including 5.18/1, only applies to the built-in operators and not to any overloaded function.
(A compliant compiler could always evaluate the operands to an overloaded
operator ,()
left to right though.)