How use alignof to force alignment for a heap allocation?

删除回忆录丶 提交于 2019-12-04 05:24:55

问题


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

int *p = new alignas(64) int;

but none of my compilers seem to give p an address that's a multiple of 64. Here's how I'm checking:

#include <iostream>

int main()
{
  int *p = new alignas(64) int;
  std::cout << long(p) % 64 << '\n';    // should print 0
}

I must be doing something wrong. But what?


回答1:


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.)




回答2:


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.



来源:https://stackoverflow.com/questions/21895038/how-use-alignof-to-force-alignment-for-a-heap-allocation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!