Skip to main content
 首页 » 编程设计

c++之写入新值是预增量表达式的 "value computation"的一部分,还是 "side effect"

2024年11月24日20davidwang456

考虑以下表达式(带有用于说明的声明):

int n = 42; 
--n &= 0x01; 

这是否违反了排序规则?

在我看来,作为左侧操作数的“值计算”的一部分,需要预增量。如果这是真的,那么自 C++11 起就没有 UB(并且,自 C++17 起,值计算和副作用都相对于赋值进行排序)。

如果是后增量,则修改 n将只是一个副作用,我们不会有很好的排序(直到 C++17)。

请您参考如下方法:

我想你是对的,这是标准所说的:
8.5.18 赋值和复合赋值运算符

All require a modifiable lvalue as their left operand; their result is an lvalue referring to the left operand. [...] 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.


所以从上面看,赋值似乎是值表达式,赋值的左右两边都在赋值之前进行评估。
从关于预增量的标准:
8.5.2.2 增减

The result is the updated operand; it is an lvalue, and it is a bit-field if the operand is a bit-field. The expression ++x is equivalent to x+=1.


这意味着即使在 C++17 之前,它的副作用也会在值计算之前排序。