如何正确使用std::align

How to properly use std::align

我认为 std::align 作为运行时地址计算以满足我的程序的进一步逻辑是否正确,即如果程序逻辑不考虑任何特定对齐,它不会使用 std::align?

的意义

使用std::align会影响代码生成吗?我的理解是否正确,与 C++20 中的 std::assume_aligned 不同,std::align 不是对编译器的提示?

std::align是一个普通的自由函数。这不是编译器提示,不涉及魔法。它确实会影响代码生成,因为任何其他函数都可能影响代码生成,即它可能会被内联、重新排序等,但不会以任何特定方式发生。

关于函数的作用和使用时间(cppreference):

Given a pointer ptr to a buffer of size space, returns a pointer aligned by the specified alignment for size number of bytes and decreases space argument by the number of bytes used for alignment. The first aligned address is returned.

因此它是运行时构造,它对 return 可用于所需对齐的地址进行一些指针运算。想象一下,你想在某个内存地址存储一个 std::int64_t,但你不知道它是否已经正确对齐(因为它在一些分配有 std::malloc 的缓冲区的中间),然后 std::align是你的朋友。

这是 libstdcxx 的实现:

inline void*
align(size_t __align, size_t __size, void*& __ptr, size_t& __space) noexcept
{
  if (__space < __size)
    return nullptr;
  const auto __intptr = reinterpret_cast<uintptr_t>(__ptr);
  const auto __aligned = (__intptr - 1u + __align) & -__align;
  const auto __diff = __aligned - __intptr;
  if (__diff > (__space - __size))
    return nullptr;
  else
    {
      __space -= __diff;
      return __ptr = reinterpret_cast<void*>(__aligned);
    }
}

它用于例如在 std::monotonic_buffer_resource::do_allocate - 这正是此功能的用例。