Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly use std::align

Is it correct that I consider std::align as a runtime address calculation to meet the further logic of my program, i.e. if the program logic doesn't take into account any specific alignment, it doesn't make sense to use std::align?

Does using of std::align affect code generation? Is my understanding correct that, unlike std::assume_aligned from C++20, std::align is not a hint to a compiler?

like image 221
Rom098 Avatar asked Oct 17 '25 11:10

Rom098


1 Answers

std::align is an ordinary free function. It's not a compiler hint, no magic involved. It does affect code generation as any other function possibly affect code generation, i.e. it might be inlined, reordered etc., but not in any particular way.

As to what the function does and when it is used (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.

So its is runtime construct that does some pointer arithmetic to return an address that is usable for a desired alignment. Imagine you want to store a std::int64_t at some memory address, but you don't know whether it's already correctly aligned (because it's in the middle of some buffer allocated with std::malloc), then std::align is your friend.

Here's the libstdcxx implementation:

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);
    }
}

It is used e.g. in std::monotonic_buffer_resource::do_allocate - which is exactly the use case this function was made for.

like image 174
lubgr Avatar answered Oct 19 '25 02:10

lubgr