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也是非法的,access to an object of another type也是非法的†,这使得通过未对齐的指针访问 UB。
† unsigned char
、char
和 std::byte
关于c++ - 基于对准要求的优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49597586/