简体   繁体   中英

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

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM