gpt4 book ai didi

c++ - C++11 中的新序列点

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:11:03 24 4
gpt4 key购买 nike

随着新的大学学年的到来。
我们已经开始收到标准的为什么 ++ i++ 不能按预期工作的问题。

在回答了其中一个这类问题后,我被告知新的 C++11 标准已经改变,这不再是未定义的行为。我听说 sequence points 已被 sequenced beforesequenced after 所取代,但没有深入(或根本没有)阅读主题。

所以我刚才回答的问题有:

int i = 12;
k = ++ (++ i);

那么问题是:

序列点在 C++11 中如何变化,它如何影响上述问题。它仍然是未定义的行为还是现在已明确定义?

最佳答案

这些情况下的 UB 基于 [intro.execution]/15

Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced. [...] The value computations of the operands of an operator are sequenced before the value computation of the result of the operator. If a side effect on a scalar object is unsequenced relative to either another side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined.

对于 ++(++i):[expr.pre.incr]/1 指出 ++i 被定义为 i+=1。这导致 [expr.ass]/1,它说

In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression.

因此,对于++(++i),等同于(i+=1)+=1,内部赋值顺序在外部赋值之前,并且我们没有 UB。


[intro.execution]/15有一个UB的例子:

i = i++ + 1; // the behavior is undefined

这里的情况有点不同(感谢 Oktalist 指出这里的前后缀错误)。 [expr.post.incr]/1 描述了 postfix 增量的效果。它指出:

The value computation of the ++ expression is sequenced before the modification of the operand object.

但是,副作用(i的修改)的顺序没有要求。这种要求也可以由赋值表达式强加。但是赋值表达式只需要在赋值之前对操作数的值计算(而不是副作用)进行排序。因此,通过 i = ..i++ 进行的两次修改是无序的,我们得到了未定义的行为。

注意i = (i = 1); 有同样的问题:内部赋值保证 i = 1 的副作用在排序之前相同表达式的值计算。并且外部赋值需要该值,这保证它(右操作数 (i = 1) 的值计算)在外部赋值的副作用之前排序。同样,i =++i + 1;(等同于 i = (i+=1) + 1;)具有定义的行为。


逗号运算符是副作用排序的示例; [表达式.逗号]/1

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.

[intro.execution]/15 包含示例 i = 7, i++, i++;(阅读:(i=7), i++, i++;),这是已定义的行为(i 变为 9)。

关于c++ - C++11 中的新序列点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19069681/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com