I have an array which is used as the underlying memory of an object of type T:
char memory[sizeof T];
.
.
.
new(memory) T(whatever);
How can I make sure memory is aligned correctly for T objects? In C++0x I could just say:
alignas(T) char memory[sizeof T];
but Visual Studio 2010 does not support that particular feature yet.
The usual (portable) solution is to put the memory declaration in a union with whatever built-in type in
Trequires the most alignment.The simplest way would be to use a union with all of the likely
candidates:
I’ve yet to hear about, much less encounter, a machine where the above
didn’t suffice. Generally, just
doublesuffices. (It is definitelysufficient on Intel and on Sparc.)
In some extreme cases, this can result in allocating more memory than
necessary, e.g. if
Tonly contains one or twochar. Most of thetime, this really doesn’t matter, and isn’t worth worrying about, but if
it is, the following can be used:
In this case,
MaxAlignFor<T>will never be bigger thanT(and to have sufficient alignment, since the required alignment will
never be larger than the size of
T).Note that none of this is formally guaranteed by the standard. But it
will work in practice.