6.4 KiB
[dcl.align]
9 Declarations [dcl]
9.13 Attributes [dcl.attr]
9.13.2 Alignment specifier [dcl.align]
An alignment-specifier may be applied to a variable or to a class data member, but it shall not be applied to a bit-field, a function parameter, or an exception-declaration ([except.handle]).
An alignment-specifier may also be applied to the declaration of a class (in anelaborated-type-specifier ([dcl.type.elab]) orclass-head ([class]), respectively).
An alignment-specifier with an ellipsis is a pack expansion ([temp.variadic]).
When the alignment-specifier is of the formalignas( constant-expression ):
the constant-expression shall be an integral constant expression
if the constant expression does not evaluate to an alignment value ([basic.align]), or evaluates to an extended alignment and the implementation does not support that alignment in the context of the declaration, the program is ill-formed.
An alignment-specifier of the formalignas( type-id ) has the same effect as alignas(alignof( type-id )).
The alignment requirement of an entity is the strictest nonzero alignment specified by its alignment-specifiers, if any; otherwise, the alignment-specifiers have no effect.
The combined effect of all alignment-specifiers in a declaration shall not specify an alignment that is less strict than the alignment that would be required for the entity being declared if all alignment-specifiers appertaining to that entity were omitted.
[Example 1: struct alignas(8) S {};struct alignas(1) U { S s;}; // error: U specifies an alignment that is less strict than if the alignas(1) were omitted. â end example]
If the defining declaration of an entity has analignment-specifier, any non-defining declaration of that entity shall either specify equivalent alignment or have noalignment-specifier.
Conversely, if any declaration of an entity has analignment-specifier, every defining declaration of that entity shall specify an equivalent alignment.
No diagnostic is required if declarations of an entity have different alignment-specifiers in different translation units.
[Example 2: // Translation unit #1:struct S { int x; } s, *p = &s;
// Translation unit #2:struct alignas(16) S; // ill-formed, no diagnostic required: definition of S lacks alignmentextern S* p; â end example]
[Example 3:
An aligned buffer with an alignment requirement of A and holding N elements of type T can be declared as:alignas(T) alignas(A) T buffer[N];
Specifying alignas(T) ensures that the final requested alignment will not be weaker than alignof(T), and therefore the program will not be ill-formed.
â end example]
[Example 4: alignas(double) void f(); // error: alignment applied to functionalignas(double) unsigned char c[sizeof(double)]; // array of characters, suitably aligned for a doubleextern unsigned char c[sizeof(double)]; // no alignas necessaryalignas(float)extern unsigned char c[sizeof(double)]; // error: different alignment in declaration â end example]