I do not understand the reason for aligning the char [] buffer with an object of type X in the code below

Stroustrup in his new book on page 151 shows the following example of using the alignas type alignas :

Sometimes we need to use alignment in a declaration where an expression such as alignof (x + y) is not allowed. Instead, we can use a qualifier like alignas: alignas (T) means "align just like T". For example, we can allocate uninitialized storage for some type X, for example:

 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); ... } 
+6
source share
1 answer

The buffer is of type char and therefore will be aligned for char , but it actually wants to keep X in it, and X may need other alignment to char , and therefore the alignas specifier allows it to make sure that it is correctly aligned for X objects.

+1
source

Source: https://habr.com/ru/post/977887/


All Articles