Stroustrup in his new book in page 151 shows the following example of the use of the type specifier alignas
:
Sometimes, we have to use alignment in a declaration, where an expression, such as alignof(x+y) is not allowed. Instead, we can use the type specifier alignas: alignas(T) means "align just like a T." For example , we can set aside uninitialized storage for some type X like this:
void user(const vector<X>& vx)
{
constexpr int bufmax = 1024;
alignas(X) char buffer[bufmax]; // unitialized
const int max = min(vx.size(), bufmax/sizeof(X));
unitialized_copy(vx.begin(), vx.begin() + max, buffer);
...
}
The buffer is of type char
and so will be aligned for char
but he actually wants to store X
in it and X
may require a different alignment to char
and so the alignas
specifier allows him to ensure it is correctly aligned for X
objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With