Stroustrup 在他的新书第 151 页中展示了以下使用类型说明符 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);
...
}
最佳答案
缓冲区是 char
类型,因此将对齐 char
但他实际上想在其中存储 X
和 X
可能需要与 char
不同的对齐方式,因此 alignas
说明符允许他确保它为 X
对象正确对齐。
关于c++ - 我不明白在下面的代码中将 char buffer[] 与 X 类型的对象对齐的原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26806376/