基于对准要求的优化

optimization based on alignment requirements

根据[basic.align]

Object types have alignment requirements ([basic.fundamental], [basic.compound]) which place restrictions on the addresses at which an object of that type may be allocated.

我希望允许 C++ 编译器假定任何指向 T 的指针都指向正确对齐的 T。

例如(如果 alignof(int) == 4)

int* p = /* ... */
auto val = p[0];
if ((reinterpret_cast<std::uintptr_t>(p) & 3) != 0) {
   // assumed to be unreachable
}

但是,在编译器资源管理器中测试 GCC 和 clang,我没有看到它们中的任何一个做出这个假设。 即使我取消引用指针(如果未正确对齐,这肯定会导致 UB),也不会做出此指针值假设。

我知道指针到整数值的映射是实现定义的,并且编译器可能有一个不同于此代码假定的映射(尽管我不这么认为)。

我还认识到,如果做出这个假设,生产中可能会有很多代码会中断,这解释了为什么这些编译器目前没有这样做。

我的问题是:根据标准,编译器可以做出有效假设吗?

如果不是,请引用标准!

编辑:阐明了指针已取消引用。

EDIT2:说 alignof() (而不是 sizeof())

是的,编译器可能假定指针正确对齐。

让我们暂时假设有一个函数 is_aligned 测试指针指向的地址是否与其类型正确对齐。

int* p = /* ... */
auto val = p[0];
if (is_aligned(p)) {
   // assumed to be unreachable
}

那就是真的。我们从 [basic.life]

推导出这个

The lifetime of an object of type T begins when:

  • storage with the proper alignment and size for type T is obtained [...]

因此不存在对齐不正确的对象。 It then follows 指针是空指针、无效指针或指向另一种类型的对象。

通过空指针访问是非法的,access through invalid pointers is also illegal, and so is access to an object of another type,这使得通过未对齐的指针访问UB。

unsigned charcharstd::byte

除外