How do I check a typed pointer is properly aligned for that type?

别说谁变了你拦得住时间么 提交于 2020-02-24 11:51:27

问题


Suppose I have a templated function that deals with pointers to yet unknown type T. Now if type T happens to be void* on 64-bit platform then it must be 8-bytes aligned, but if T happens to be char it must be 1-byte aligned and if T happens to be a class then its alignment requirements will depend on its member variables.

This all can be computed on paper, but how do I make the compiler yield the alignment requirements for a given type T?

Is there a way to find during compile time the alignment requirements for a given type?


回答1:


In C++11 you can use alignof and alignas to make asserts and provide requirements for alignment. Also look at std::align to control alignment in runtime.




回答2:


In the absence of C++11, its easiest to use the next power-of-two greater than or equal to sizeof(T). You might also want to cap it to the alignment of the largest primitive. 8 is a pretty safe bet on a 64-bit architecture (though you might need to keep an eye on things like SSE data types).



来源:https://stackoverflow.com/questions/13249841/how-do-i-check-a-typed-pointer-is-properly-aligned-for-that-type

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