c++ - 如何以独立于平台的方式设置对齐方式?

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

latest draft of the c++11 standard ,第3.11章讲到对齐。
稍后,第 7.6.1 章定义了如何定义对齐结构(或变量?)

如果我定义这样的结构:

alignas(16) struct A
{
  int n;
  unsigned char[ 1020 ];
};

这是否意味着 A 类的所有实例都将对齐到 16 字节?

或者,我必须像在下一个代码中那样做吗?

struct A
{
  char data[300];
};
alignas(16) A a;

如果两个例子都是错误的,如何正确地做?

PS 我不是在寻找依赖于编译器的解决方案。

最佳答案

对齐首先是类型的属性。

可以用 alignas 覆盖类型; alignas 也可以用于为特定对象分配新的对齐值。

因此,这两个示例都是有效的,并且将具有您假定的语义。

[n3290: 3.11/1]: Object types have alignment requirements (3.9.1, 3.9.2) which place restrictions on the addresses at which an object of that type may be allocated. An alignment is an implementation-defined integer value representing the number of bytes between successive addresses at which a given object can be allocated. An object type imposes an alignment requirement on every object of that type; stricter alignment can be requested using the alignment specifier (7.6.2).

[n3290: 7.6.2/1]: An alignment-specifier may be applied to a variable or to a class data member, but it shall not be applied to a bit-field, a function parameter, the formal parameter of a catch clause (15.3), or a variable declared with the register storage class specifier. An alignment-specifier may also be applied to the declaration of a class or enumeration type. An alignment-specifier with an ellipsis is a pack expansion (14.5.3).

[n3290: 7.6.2/2]: When the alignment-specifier is of the form alignas( assignment-expression ):

  • the assignment-expression shall be an integral constant expression
  • if the constant expression evaluates to a fundamental alignment, the alignment requirement of the declared entity shall be the specified fundamental alignment
  • if the constant expression evaluates to an extended alignment and the implementation supports that alignment in the context of the declaration, the alignment of the declared entity shall be that alignment
  • if the constant expression evaluates to an extended alignment and the implementation does not support that alignment in the context of the declaration, the program is ill-formed
  • if the constant expression evaluates to zero, the alignment specifier shall have no effect
  • otherwise, the program is ill-formed.

关于c++ - 如何以独立于平台的方式设置对齐方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7501211/

相关文章:

c - 在字对齐处理器上处理未对齐数据的最快方法?

c++ - CentOS 6.5 秒杀

c++ - 大多数基本类型的高效二进制序列化

c++ - 对类中函数的 undefined reference

c++ - 如何在不将非法输入替换为替换字符的情况下解码 UTF-8?

c++ - 如何将 "extern template"与由同一类中的模板化成员使用的嵌套类一起使用?

c++ - 使用 g++7 构建的代码因访问未对齐的内存而崩溃

c - 在编写干净的 C 代码时利用 ARM 未对齐的内存访问

c++ - 在 C++ 中将函数作为参数执行

c++ - 哪些 C 结构出现在 std 命名空间中?