Boost C++ Libraries

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

This is the documentation for an old version of Boost. Click here to view this page for the latest version.
PrevUpHomeNext

aligned_storage

template <std::size_t Size, std::size_t Align>
struct aligned_storage
{
   typedef see-below type;
};

type: a built-in or POD type with size Size and an alignment that is a multiple of Align.

Header: #include <boost/type_traits/aligned_storage.hpp> or #include <boost/type_traits.hpp>

On the GCC and Visual C++ compilers (or compilers that are compatible with them), we support requests for types with alignments greater than any built in type (up to 128-bit alignment). Visual C++ users should note that such "extended" types can not be passed down the stack as by-value function arguments.

[Important] Important

Visual C++ users should be aware that MSVC has an elastic definition of alignment, for example consider the following code:

typedef boost::aligned_storage<8,8>::type align_t;
assert(boost::alignment_of<align_t>::value % 8 == 0);
align_t a;
assert(((std::uintptr_t)&a % 8) == 0);
char c = 0;
align_t a1;
assert(((std::uintptr_t)&a1 % 8) == 0);

In this code the final assert will fail for a 32-bit build because variable a1 is not aligned on an 8-byte boundary. Had we used the MSVC intrinsic __alignof in place of alignment_of or std::aligned_storage in place of boost::aligned_storage the result would have been no different. In MSVC alignment requirements/promises only really apply to variables on the heap, not on the stack.

Further, although MSVC has a mechanism for generating new types with arbitrary alignment requirements, such types cannot be passed as function arguments on the program stack. Therefore had boost::aligned_storage<8,8>::type been a type declared with __declspec(align(8)) we would break a great deal of existing code that relies on being able to pass such types through the program stack.


PrevUpHomeNext