将一些连续的数组单元读取为更大的类型是不是很麻烦?

It it UB to read some contiguous array cells as a larger type?

char foo[n] = /*init here*/;  // n = 4*k + 4.
int i = 0;
while (i < n) {                            
   int four_bytes = *reinterpret_cast<const int*>(foo + i); // is this UB?
   bar(four_bytes);
   i += 4; 
}

在这段代码中(假设所有数据都正确初始化,并且数组的长度是 4 的倍数),这是 reinterpret_cast UB 吗?

C++14 有时是 C++11

对齐方式

char foo[n] 作为 int 数组没有充分对齐时,它是 UB。

尺寸1

0 < n < sizeof(int) 时,*reinterpret_cast<const int*>(foo + i); 尝试在 foo[] 外引用。


1 直到后来才看到“array's length is a multiple of 4”。然而,这仍然适用于 sizeof int 更大的不寻常平台,比如 8。(例如,一些旧的图形处理)。 IOWs“数组的长度是 4 的倍数”未指定为与“数组的长度是 sizeof(int)”的倍数相同