Search code examples
c++alignmentc++11

Determining maximum possible alignment in C++


Is there any portable way to determine what the maximum possible alignment for any type is?

For example on x86, SSE instructions require 16-byte alignment, but as far as I'm aware, no instructions require more than that, so any type can be safely stored into a 16-byte aligned buffer.

I need to create a buffer (such as a char array) where I can write objects of arbitrary types, and so I need to be able to rely on the beginning of the buffer to be aligned.

If all else fails, I know that allocating a char array with new is guaranteed to have maximum alignment, but with the TR1/C++0x templates alignment_of and aligned_storage, I am wondering if it would be possible to create the buffer in-place in my buffer class, rather than requiring the extra pointer indirection of a dynamically allocated array.

Ideas?

I realize there are plenty of options for determining the max alignment for a bounded set of types: A union, or just alignment_of from TR1, but my problem is that the set of types is unbounded. I don't know in advance which objects must be stored into the buffer.


Solution

  • In C++0x, the Align template parameter of std::aligned_storage<Len, Align> has a default argument of "default-alignment," which is defined as (N3225 §20.7.6.6 Table 56):

    The value of default-alignment shall be the most stringent alignment requirement for any C++ object type whose size is no greater than Len.

    It isn't clear whether SSE types would be considered "C++ object types."

    The default argument wasn't part of the TR1 aligned_storage; it was added for C++0x.