Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining maximum possible alignment in C++

Tags:

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.

like image 789
jalf Avatar asked Oct 06 '09 19:10

jalf


2 Answers

In C++11 std::max_align_t defined in header cstddef is a POD type whose alignment requirement is at least as strict (as large) as that of every scalar type.

Using the new alignof operator it would be as simple as alignof(std::max_align_t)

like image 190
Ricky65 Avatar answered Sep 23 '22 00:09

Ricky65


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.

like image 33
James McNellis Avatar answered Sep 23 '22 00:09

James McNellis