在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 theregister
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 formalignas( 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/