I want to know the alignment guarantees of a statically allocated array of char. Looking at other SO questions, I found some concerning dynamically allocated arrays of char.
For statically allocated char arrays, are they aligned such that I can placement new any type into it (provided it is sufficiently large)? Or does this only apply for dynamically allocated ones?
char buff[sizeof(T)];
T * pT = (T*) buff;
new(pT) T(); // well defined?
...
pT->~T();
If not, how can I overcome this problem?
If you want to guarantee the alignment of the static char array, you can use the union trick.
Here the alignment will be guaranteed for the largest element in the union. And of course you should wrap this nastiness away in a nice class.
Edit: better answer:
Of course you’d be even better using
boost::aligned_storageoralignasfor C++11.