Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I don't understand the reason for the alignment of the char buffer[] with an object of type X in the code below

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);
    ...
}
like image 999
Belloc Avatar asked Nov 07 '14 17:11

Belloc


1 Answers

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.

like image 158
sjdowling Avatar answered Sep 30 '22 17:09

sjdowling