Learn About Using Alignment Support In C++Builder For Robust Windows Development

The alignment requirement of a type is a divisor of its size. For example, a class with size 16 bytes could have an alignment of 1, 2, 4, 8, or 16, but not 32. (If a class’s members only total 14 bytes in size, but the class needs to have an alignment requirement of 8, the compiler will insert 2 padding bytes to make the class’s size equal to 16.). C++11 standard intends to extend the standard language and library with alignment-related features.

Querying the alignment of a type

The alignment requirement of a type can be queried using the alignof keyword as a unary operator. The result is a constant expression of type std::size_ti.e., it can be evaluated at compile time.

Possible output : The alignment requirement of int is: 4

Controlling alignment

The alignas keyword can be used to force a variable, class data member, declaration or definition of a class, or declaration or definition of an enum, to have a particular alignment, if supported. It comes in two forms:

alignas(x), where x is a constant expression, gives the entity the alignment x, if supported.
alignas(T), where T is a type, gives the entity an alignment equal to the alignment requirement of T, that is, alignof(T), if supported.

If multiple alignas specifiers are applied to the same entity, the strictest one applies. In this example, the buffer buf is guaranteed to be appropriately aligned to hold an int object, even though its element type is unsigned char, which may have a weaker alignment requirement.

alignas cannot be used to give a type a smaller alignment than the type would have without this declaration:

Head over and check out more information about C++ alignment support in C++Builder.