c++ - 我不明白在下面的代码中将 char buffer[] 与 X 类型的对象对齐的原因

标签 c++ c++11 memory-alignment

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/

相关文章:

c++ - 在编译时选择全局作用域函数

c++ - 在运行时检测负载是否是原子的?

c - C中的默认 union 和结构对齐?

c++ - boost spirit 难度,从 XML 示例开始

c++ - 如何在基类中创建同名的两个函数?

c++ - 从模板基类派生的类的隐式转换

c++ - 消除可变类层次结构中无参数函数调用的歧义

C++:分配对齐矩阵

c++ - C++ 中容器内过度对齐的结构和枚举之间的差异

c++ - 如何在 Windows 中获取硬盘当前负载信息?