且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

幻像类型与原始类型具有相同的对齐方式吗?

更新时间:2023-10-26 16:26:28

该标准在 [basic.align]/1 :

对象类型具有对齐要求(3.9.1、3.9.2),这些要求放在 对该类型的对象可能位于的地址的限制 已分配. 对齐方式是实现定义的整数值 代表连续地址之间的字节数 可以分配给定的对象.对象类型强制对齐 对该类型的每个物体的要求;可以更严格地对齐 使用对齐说明符(7.6.2)请求.

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).

此外, [basic.compound]/3 提到:

指针类型的值表示形式是实现定义的. 指向 layout-compatible类型的指针应具有相同的值 表示和对齐要求(6.11). [注意:指向 过度对齐的类型(6.11)没有特殊的表示形式,但是它们的 有效值范围受扩展对齐方式的限制 要求].

The value representation of pointer types is implementation-defined. Pointers to layout-compatible types shall have the same value representation and alignment requirements (6.11). [Note: Pointers to over-aligned types (6.11) have no special representation, but their range of valid values is restricted by the extended alignment requirement].

因此,可以保证与布局兼容的类型具有相同的对齐方式.

As a result, there is a guarantee that layout-compatible types have the same alignment.

struct { T m; }T与布局不兼容.

如指出的那样

As pointed here, in order for two elements to be layout compatible then they both have to be standard-layout types, and their non-static data members must occur with the same types and in the same order.

struct { T m; }仅包含T,但是TT,因此它不能包含T作为其第一个非静态数据成员.

struct { T m; } contains just a T, but T is a T so it cannot contain a T as its first non-static data member.