开发者

How to set the alignment in a platform independent way?

In the latest draft of the c++11 standard, chapter 3.11 talks about the alignment.

Later, the chapter 7.6.1 defines how to define an aligned structures (or variables?)

If I define a structure like this :

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

does it means that all instances of the class A ar开发者_如何转开发e going to be aligned to 16 bytes?

Or, do I have to do it like in the next code?

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

If both examples are wrong, how to do it properly?

PS I am not looking for a compiler dependent solution.


Alignment is first and foremost a property of types.

It can be overridden for a type with alignas; alignas can also be used to assign a new alignment value to a specific object.

So, both examples are valid, and will have the semantics that you've presumed.

[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.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜