How to check the entered pointer is correctly aligned for this type?

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

All this can be calculated on paper, but how to get the compiler to fulfill the alignment requirements for a given type T ?

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

+2
source share
2 answers

In C ++ 11, you can use alignof and alignas to state and provide alignment requirements. Also see std :: align for control of alignment at runtime.

+4
source

In the absence of C ++ 11, it’s easiest to use the following power β€” two, greater than or equal to sizeof(T) . You can also limit it to aligning the largest primitive. 8 is a pretty safe bet on 64-bit architecture (although you may need to keep an eye on things like SSE data types).

+2
source

Source: https://habr.com/ru/post/1013614/


All Articles