How use alignof to force alignment for a heap allocation?

前端 未结 2 1672
梦毁少年i
梦毁少年i 2021-01-24 02:03

I\'d like to force a specific heap allocation to return an address that\'s 64-byte aligned, because that\'s a cache line boundary. I thought I could do it like this



        
相关标签:
2条回答
  • 2021-01-24 02:26

    Ask for 64 more bytes than you need, then generate a cache aligned address within the allocated space. Taking care to free the whole allocated memory at the end.

    0 讨论(0)
  • 2021-01-24 02:30

    The allocator called by the new operator in order to allocate space is "assumed to return pointers to storage that is appropriately aligned for objects of any type with fundamental alignment" (§3.7.4.1/2; quote is from §5.3.4/11). alignas(64) is probably not a "fundamental alignment" for your compiler and environment, so the allocation function doesn't need to respect it.

    Note that the allocation function is only passed the amount of space requested; it has no idea what alignment is being requested. Consequently, it cannot adjust its result to fit special needs.

    The alignas type specifier is designed to work with static and automatic objects. With such objects, the requested alignment must be respected if it is fundamental, and in an ideal world the compiler would produce an error message if it cannot guarantee that an extended alignment would be respected. (I don't believe it's obliged to do so, though; both gcc and clang produce executables which segfault if a huge stack-alignment is requested.)

    0 讨论(0)
提交回复
热议问题