Alignas in C++ 11
Last Updated :
06 Oct, 2023
The alignas is a type specifier which was introduced in C++11. It provides custom alignment to variables and user-defined datatypes like class and struct. Alignment refers to the memory address at which an object’s data should begin. alignas allows the programmer to control how the compiler aligns data in memory. It may allocate memory address in modulo power of 2 to improve performance, especially on architectures that require data to be aligned.
Syntax
alignas( Integral_constant_expression )
The alignas Specifier applies for:
- Declaration or definition of a struct, class, union, enum.
- Declaration of a non-bitfield class data member.
- Declaration of a variable, except
- a function parameter.
- the exception parameter of a catch clause.
Note: We would require the knowledge of alignof specifier to work with our example.
Example of alignas Specifier
C++
#include <iostream>
using namespace std;
struct alignas(16) Demo
{
int var1l;
int var2;
short s;
alignas(4) char arr[5];
};
int main()
{
cout << alignof(Demo) << endl;
return 0;
}
|
Explanation
Here, the output is 16, solely because we have used alignas(16) for the struct Demo. But what about the various member inside the struct? For example, int var1 and int var2 are int types and it is aligned to 4 bytes. Also, alignas(4) char arr[5] specifies that the ‘char’ array needs to be aligned to 4 bytes (instead of 1 byte).
So the compiler decides to choose the largest (in other words, strictest) alignment requirement among the members and the struct itself. Hence, 16 which is the largest alignment, is chosen as output when alignof operator is called on struct Demo. Finally, we get to know that all objects of the Demo struct will be aligned to 16 byte boundaries in memory.
Practice: Try to use sizeof(Demo) and compare it with alignof(Demo) and check the difference if any.
Real Time Use Cases of alignas
The alignas specifier is generally used to the following cases:
- To avoid unnecessary invalidation of your data from cache lines in multi-threaded application.
- To optimize the CPU reads such that wastage of CPU cycles can be saved.
- To implement custom memory layout.
Share your thoughts in the comments
Please Login to comment...