为什么内联类型的链接前缀增量/减量不是UB的C ++? [英] Why chained prefix increment/decrement for builtin type is not UB for C++?

查看:235
本文介绍了为什么内联类型的链接前缀增量/减量不是UB的C ++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在cpprefernce.com中示例中的前缀增量有以下代码:

In cpprefernce.com example for prefix increment there is such code:

int n1 = 1;
...
int n3 = ++ ++n1;

为什么在这种情况下链接增量不会导致UB?

Why chained increment in this case does not lead to UB? Is rule for at most once modified not violated in this case?

推荐答案

在C ++ 11及更高版本中,UB发生在是两个写,或者一个写和一个读不顺序并访问相同的存储器位置。但 ++ x 等效于 x + = 1 ,因此 ++ ++ n1 等价于(n1 + = 1)+ = 1 ,这里的读写操作由于赋值和化合物的属性赋值运算符:首先读取 n1 ,然后写入一个加上原始值,然后再次读取结果值,然后写回一个值。

In C++11 and later, UB occurs when there are two writes or a write and a read that are unsequenced and access the same memory location. But ++x is equivalent to x+=1, so ++ ++n1 is equivalent to (n1+=1)+=1, and here the reads and writes happen in a strict sequence because of the properties of assignment and compound assignment operators: first n1 is read, then one plus the original value is written, then the resulting value is read again, then one plus that value is written back.

在C ++ 03中,此 UB,因为您引用的旧规则:两个修改之间没有序列点。但在C ++ 11中不再有任何序列点;而是存在顺序之前部分顺序。

In C++03, this was UB, because of the old rule you allude to: there is no sequence point between the two modifications. But in C++11 there are no longer any sequence points; instead there is the "sequenced before" partial order.

这篇关于为什么内联类型的链接前缀增量/减量不是UB的C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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