How to adjust alignment on the platform independently?

In the final draft of the C ++ 11 standard , chapter 3.11 talks about alignment.
Chapter 7.6.1 later defines how to define aligned structures (or variables?)

If I define the structure as follows:

alignas(16) struct A { int n; unsigned char[ 1020 ]; }; 

Does this mean that all instances of class A will be aligned with 16 bytes?

Or do I need to do this, as in the following code?

 struct A { char data[300]; }; alignas(16) A a; 

If both examples are wrong, how to do it right?

PS I'm not looking for a compiler dependent solution.

+4
source share
1 answer

Alignment is, first of all, a property of types.

It can be overridden for a type with alignas ; alignas can also be used to assign a new alignment value to a specific object.

So, both examples are valid and will have the semantics that you suggested.

[n3290: 3.11/1]: Object types have alignment requirements (3.9.1, 3.9.2) that set limits on the addresses where this type can be allocated. Alignment is an implementation-defined integer value that represents the number of bytes between consecutive addresses where this object can be allocated. An object type imposes an alignment requirement for each object of this type; more stringent alignment can be requested using the alignment specifier (7.6.2).

[n3290: 7.6.2/1]: The alignment [n3290: 7.6.2/1]: can be applied to a variable or data element of a class , but it does not apply to a bit field, function parameter, formal catch parameter (15.3), or a variable declared by the storage class register specifier. An alignment specifier can also be applied to a class or type declaration of an enumeration. The alignment specifier with an ellipsis is a package extension (14.5.3).

[n3290: 7.6.2/2]: When the alignment specifier is of the form alignas( assignment-expression ):

  • assignment expression must be an integral constant expression
  • if the expression of the constant is fundamental alignment, the requirement of matching the declared object must be the specified basic alignment
  • if a constant expression evaluates to advanced alignment and the implementation supports this alignment in the context of the declaration, the alignment of the declared object should be such that alignment
  • if the constant expression is evaluated with extended alignment and the implementation does not support this alignment in the context of the declaration, the program is poorly formed.
  • if the constant expression evaluates to zero, the alignment specifier should have no effect
  • otherwise the program is poorly formed.
+3
source

All Articles