...one of the most highly
regarded and expertly designed C++ library projects in the
world.
— Herb Sutter and Andrei
Alexandrescu, C++
Coding Standards
Object types have alignment requirements which place restrictions on the addresses at which an object of that type may be allocated. An alignment is an implementation-defined integer value representing the number of bytes between successive addresses at which a given object can be allocated. An object type imposes an alignment requirement on every object of that type; stricter alignment can be requested using the alignment specifier.
A fundamental alignment is represented by
an alignment less than or equal to the greatest alignment supported by the
implementation in all contexts, which is equal to alignof(std::max_align_t)
.
The alignment required for a type might be different when it is used as the
type of a complete object and when it is used as the type of a subobject.
Tip | |
---|---|
struct B { long double d; }; struct D : virtual B { char c; };
When |
The result of the alignof
operator
reflects the alignment requirement of the type in the complete-object case.
An extended alignment is represented by an
alignment greater than alignof(std::max_align_t)
.
It is implementation-defined whether any extended alignments are supported
and the contexts in which they are supported. A type having an extended alignment
requirement is an over-aligned type.
Note | |
---|---|
Every over-aligned type is or contains a class type to which extended alignment applies (possibly through a non-static data member). |
Alignments are represented as values of the type std::size_t
.
Valid alignments include only those values returned by an alignof
expression for the fundamental types plus an additional implementation-defined
set of values, which may be empty. Every alignment value shall be a non-negative
integral power of two.
Alignments have an order from weaker to stronger or stricter alignments. Stricter alignments have larger alignment values. An address that satisfies an alignment requirement also satisfies any weaker valid alignment requirement.
The alignment requirement of a complete type can be queried using an alignof
expression. Furthermore, the types
char
, signed
char
, and unsigned
char
shall have the weakest alignment
requirement.
Note | |
---|---|
This enables the character types to be used as the underlying type for an aligned memory area. |
Comparing alignments is meaningful and provides the obvious results:
Note | |
---|---|
The runtime pointer alignment function can be used to obtain an aligned pointer within a buffer; the aligned-storage templates in the library can be used to obtain aligned storage. |
If a request for a specific extended alignment in a specific context is not supported by an implementation, the program is ill-formed. Additionally, a request for runtime allocation of dynamic storage for which the requested alignment cannot be honored shall be treated as an allocation failure.