C++17 中 aligned_alloc 后还需要 __builtin_assume_aligned 吗?
结论
aligned_alloc(64, size) 成功时会返回 64 字节对齐的地址,所以从正确性上说,不需要 __builtin_assume_aligned。这个内建函数用于告诉 GCC 指针的对齐情况,可能帮助优化器利用该信息。GCC 能否从 aligned_alloc 调用中识别并传播对齐信息,取决于它对该调用的识别和优化,C++ 标准对此没有保证。
代码中的对齐与大小
示例将大小向上取整到 64 的倍数:
(sizeof(int8_t) * n + 63) / 64 * 64
aligned_alloc 要求 size 是 alignment 的整数倍。C++17 的 std::aligned_alloc 在 <cstdlib> 中声明。分配成功后,返回的存储会按指定的对齐值对齐;释放时使用 std::free。cppreference:std::aligned_alloc
示例使用了 aligned_alloc 这个函数名。在 C++ 中,通常通过 <cstdlib> 使用 std::aligned_alloc。有些实现也会提供全局名字,建议明确写出标准命名空间。
什么时候使用 __builtin_assume_aligned
GCC 文档说明,__builtin_assume_aligned(ptr, 64) 会返回该指针,并允许编译器假设返回的指针至少按 64 字节对齐。GCC:Other Builtins
如果 GCC 已经从分配调用及其参数推导出对齐信息,这个内建函数可能不会带来额外收益。若优化器没有传播该信息,它可以补充这一提示。它通常用于性能优化,并非 aligned_alloc 提供对齐保证所必需的步骤。是否有收益,可以通过检查目标代码或实际测量性能来判断。
使用该提示前,要确认传入的指针确实满足声明的对齐要求。aligned_alloc 分配失败时会返回空指针,因此示例中把结果传给对齐假设前,仍应先检查分配结果。向上取整计算中的加法和乘法也不能发生整数溢出。
可读性更好的写法
#include <cstddef>
#include <cstdlib>
#include <cstdint>
const std::size_t alignment = 64;
const std::size_t bytes = sizeof(int8_t) * n;
const std::size_t rounded_bytes = (bytes + alignment - 1) / alignment * alignment;
void* raw = std::aligned_alloc(alignment, rounded_bytes);
if (raw == nullptr) {
// 处理分配失败
}
auto* a = static_cast<int8_t*>(raw);
// 如有实测或编译器分析依据,可在需要时使用:
// a = static_cast<int8_t*>(__builtin_assume_aligned(a, alignment));
// 使用完毕后:
std::free(a);
还要确保 bytes + alignment - 1 不溢出,并确认 alignment 是当前实现支持的有效对齐值。代码若需跨编译器移植,就不应无条件依赖 GCC 专有的 __builtin_assume_aligned。
备注:内容仅供参考。
