C++ 中的内存对齐语法

Memory alignment syntax in C++

什么决定了 C/C++ 内存对齐语法?

我正在开发一些嵌入式应用程序,它需要 memory/data 对齐。 根据我以前的经验,对于C代码,GCC和MSVC,内存对齐语法似乎主要由编译器决定:

GCC   __attribute__ ((aligned (128)))
MSVC   __declspec(align(128))

我很好奇以下问题:

  1. 对齐语法是否还取决于其他因素,例如 OS 的目标硬件 and/or 数据模型?还是完全依赖 在编译器上?
  2. 对于 C++11,是 C++11 的新语法 alignas(128) 部分 标准,因此独立于 compiler/platform?
  3. 对于C++11,当我们对数据使用std::align时,它会做一个完整的数据吗 复制从而影响性能?
  1. 语法不会根据目标的不同而改变。
  2. 是的,alignas 自 C++11 起是 C++ 关键字,但注意:

    If the strictest (largest) alignas on a declaration is weaker than the alignment it would have without any alignas specifiers (that is, weaker than its natural alignment or weaker than alignas on another declaration of the same object or type), the program is ill-formed

    由于类型在不同平台上有不同的对齐方式,这可能适用于一个目标平台而对另一个目标平台无效:

    struct alignas(2) foo { int bar; };
    
  3. 不,std::align不复制数据。如果需要,它会修改指针和 size_t space 计数器。

    If the buffer is too small, the function does nothing and returns nullptr