标准对未对齐的内存访问有何看法?
What does the standard say about unaligned memory access?
我已经搜索过关于未对齐访问的标准,但没有找到任何东西(可能是我不小心)。
这是未定义的行为吗?是否定义了实现?
由于许多当前的 CPU 都支持未对齐的访问,因此将未对齐的内存访问定义为实现是明智的。是这样吗?
通过未对齐的访问,我的意思是例如:
alignas(int) char buffer[sizeof(int)+1];
int &x = *new(buffer+1) int;
x = 42;
不,是UB。您不能在未对齐的内存中开始对象的生命周期。来自 [basic.life]p1
The lifetime of an object of type T begins when:
storage with the proper alignment and size for type T is obtained, and
if the object has non-vacuous initialization, its initialization is complete,
[...]
因此在您的示例中,x
引用的对象的生命周期甚至没有开始,因此除了 [basic.life]p6 中提到的以外,其他任何使用都是 UB。
但是你的实现被允许做的是说未对齐的内存(由所使用的底层架构指定)实际上是对齐的,从而使你的代码在 C++ 抽象机下有效。不过,我不确定是否有任何编译器会这样做。
我已经搜索过关于未对齐访问的标准,但没有找到任何东西(可能是我不小心)。
这是未定义的行为吗?是否定义了实现?
由于许多当前的 CPU 都支持未对齐的访问,因此将未对齐的内存访问定义为实现是明智的。是这样吗?
通过未对齐的访问,我的意思是例如:
alignas(int) char buffer[sizeof(int)+1];
int &x = *new(buffer+1) int;
x = 42;
不,是UB。您不能在未对齐的内存中开始对象的生命周期。来自 [basic.life]p1
The lifetime of an object of type T begins when:
storage with the proper alignment and size for type T is obtained, and
if the object has non-vacuous initialization, its initialization is complete,
[...]
因此在您的示例中,x
引用的对象的生命周期甚至没有开始,因此除了 [basic.life]p6 中提到的以外,其他任何使用都是 UB。
但是你的实现被允许做的是说未对齐的内存(由所使用的底层架构指定)实际上是对齐的,从而使你的代码在 C++ 抽象机下有效。不过,我不确定是否有任何编译器会这样做。