alignas specifier

From cppreference.com
 
 
C++ language
General topics
Flow control
Conditional execution statements
Iteration statements
Jump statements
Functions
function declaration
lambda function declaration
function template
inline specifier
exception specifications (deprecated)
noexcept specifier (C++11)
Exceptions
Namespaces
Types
decltype specifier (C++11)
Specifiers
cv specifiers
storage duration specifiers
constexpr specifier (C++11)
auto specifier (C++11)
alignas specifier (C++11)
Initialization
Literals
Expressions
alternative representations
Utilities
Types
typedef declaration
type alias declaration (C++11)
attributes (C++11)
Casts
implicit conversions
const_cast conversion
static_cast conversion
dynamic_cast conversion
reinterpret_cast conversion
C-style and functional cast
Memory allocation
Classes
Class-specific function properties
Special member functions
Templates
class template
function template
template specialization
parameter packs (C++11)
Miscellaneous
Inline assembly
 

Specifies the alignment requirement of a type or an object.

Contents

[edit] Syntax

alignas( expression ) (since C++11)
alignas( type-id ) (since C++11)

[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 definition of a class/struct/union or enum.

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 natural alignment requirement of the type.

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.

The C language defines alignas as a preprocessor macro 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)