更新时间:2023-02-20 22:36:24
在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.