Document number: P2607R0

Date: 2022-06-14

Reply-to: Justin Cooke <jgc@cems.de>
Target audience: CWG

 

Let alignas specify minimum alignment

Proposal: relax the specification for alignas, such that specifying a weaker alignment than the implementation's default has no effect and is not an error.

 

Motivation.  The current standard states that an alignment specifier that is less strict than the default alignment for the type is an error. This rule makes it hard to specify a necessary minimum alignment for a type in a portable way.  The alignment we usually seek is max (n, d) where n is our required minimum alignment and d is the implementation’s default alignment for the type. For example, we may need an alignment of at least 8 bytes, but don’t mind if the implementation imposes 16.  But we cannot query the value of d with alignof without first defining the type.  Under the proposed change, specifying alignas(n) where n < d will have no effect and shall not be an error. Current versions of some popular compilers (such as gcc 12.1) already behave this way. 

 

Effect on existing code: None. Code that uses the proposed feature is ill-formed under strict implementations of C++20.  For implementations which already accept such code, there is no change to its semantics. 

 

Wording: (edits to 4910)

 

9.12.2 Alignment specifier                     [dcl.align]

 

...

 

5 The combined effect of all An alignment-specifiers in a declaration has no effect if it shall not specifiesy 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. OK: the alignment specifier for U has no effect.

—end example]

Remark: In the cases where the behavior specified by the current standard is desired, the effect can be achieved with a static_assert following the declaration, e.g.:

struct alignas(int) S { void* p; };

static_assert (alignof(S) == alignof(int), "alignment of S stricter than int");