c++ - 基于对准要求的优化

标签 c++ language-lawyer compiler-optimization memory-alignment

根据 [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也是非法的,access to an object of another type也是非法的,这使得通过未对齐的指针访问 UB。

unsigned charcharstd::byte

除外

关于c++ - 基于对准要求的优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49597586/

相关文章:

c++ - 窗口区域、移动的子对象、DWM 以及它可以创建的白色 block 状困惑

c++ - 通过指向成员的指针改变可变数据成员

c++ - 小字符串优化(调试与 Release模式)

clang - RISC-V 中的 LLVM 指令调度

c - 为什么调用带有字符串文字参数的纯函数未优化为常量值?

c++ - 多态失败

c++ - 二维数组不会在控制台网格中显示正确的内容

c++ - 处理动态数据结构时代码中的神秘错误

c - "producing negative zeroes"在不支持的系统中是什么意思?

c++ - 对于非空初始化,lifetime starts before initialization 解决了什么问题?