alignas specifier (since C++11)

From cppreference.com
< cpp‎ | language

Specifies the alignment requirement of a type or an object.

Contents

[edit] Syntax

alignas( expression )
alignas( type-id )

[edit] Explanation

The alignas specifier may be applied to the declaration of a variable or a class data member, or it can be applied to the declaration or definition of a class/struct/union or enumeration.

When used in form alignas(expression), and expression is an integral constant expression that evaluates to a positive value, the declared entity will have its alignment requirement set to exactly the result of the expression, except if it would weaken the alignment the type would have had without this alignas.

When used in form alignas(type), is exactly equivalent to alignas(alignof(type)), that is, the alignment requirement of the declared entity will be equal the alignment requirement of type.

[edit] Notes

alignas(0) has no effect.

When multiple alignas specifiers are applied to the same variable or class, the strictest one is used.

As of the ISO C11 standard, the C language has the _Alignas keyword and defines alignas as a preprocessor macro expanding to the keyword in the header <stdalign.h>, but in C++ this is a keyword, and the headers <stdalign.h> and <cstdalign> do not define such macro. They do, however, define the macro constant __alignas_is_defined.

[edit] Keywords

alignas

[edit] Example

// every object of type sse_t will be aligned to 16-byte boundary
struct alignas(16) sse_t
{
  float sse_data[4];
};
 
// the array "cacheline" will be aligned to 128-byte boundary
alignas(128) char cacheline[128];



[edit] See also

alignof operator queries alignment requirements of a type (since C++11)
(C++11)
obtains the type's alignment requirements
(class template)
C documentation for _Alignas