16,749
社区成员
发帖
与我相关
我的任务
分享
先看四个重要的基本概念:
1.数据类型自身的对齐值:
对于char型数据,其自身对齐值为1,byte型为1,int为4,Extended为10,单位字节。
2.结构体或者类的自身对齐值:其成员中自身对齐值最大的那个值。
3.指定对齐值:delphi编译器中配置的值,一般为1,2,4,8。
4.数据成员、结构体和类的有效对齐值:自身对齐值和指定对齐值中小的那个值。
知道了上面四个概念
假设delphi编译器指定的值为8
来分析T1和T2
对于T1:
T1 = record
b1,b2:Boolean;
ID:Integer;
v2:Extended; // 10
end;
首先b1自身对齐值1,指定值8,有效值为1,存在第1个位置
b1自身对齐值1,指定值8,有效值为1,存在第2个位置
ID自身对齐值4,指定值8,有效值为4,存在第5-8的位置(4的倍数)
v2自身对齐值10,指定值8,有效值为8,存在第9-18的位置
结束,再看整个结构体T1的自身对齐值为其中最大的值为10,指定值8,有效值为8,所以要根据8的整数倍进行圆整
,我们已经存了18个,其后补6个字节进行圆整即变为24个字节。
对于T2:
T2 = record
b1,b2:Boolean;
ID:Integer;
v1:array [0..9] of Byte; // 10
end;
首先b1自身对齐值1,指定值8,有效值为1,存在第1个位置
b1自身对齐值1,指定值8,有效值为1,存在第2个位置
ID自身对齐值4,指定值8,有效值为4,存在第5-8的位置(4的倍数)
v1按10个byte存,自身对齐值为1,指定值8,有效值为1,存在第9-18的位置
结束,再看整个结构体T2的自身对齐值为其中最大的值为4,指定值8,有效值为4,所以要根据4的整数倍进行圆整,
我们已经存了18个,其后补2个字节进行圆整即变为20个字节。
结果
T1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
b1 b2 id id id id v2 v2 v2 v2 v2 v2 v2 v2 v2 v2
T2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
b1 b2 id id id id v1 v1 v1 v1 v1 v1 v1 v1 v1 v1
其实按照这样的结构体进行对比看更容易
T1 = record
b1:Boolean;
ID:Integer;
b2:Boolean;
end;
T2 = record
ID:Integer;
b1:Boolean;
b2:Boolean;
end;
域中只是顺序变化了下
然而sizeof(t1)=12;sizeof(t2)=8
Record field alignment
Controls alignment of fields in Delphi record types and class structures. Click the down-arrow to select from the possible values:
If you select option Off (equivalent to {$A1}) or disable the option (equivalent to {$A-}), fields are never aligned. All record and class structures are packed.
If you select Byte (equivalent to {$A2}), fields in record types that are declared without the packed modifier and fields in class structures are aligned on byte boundaries. If you select Word (equivalent to {$A2}), fields in record types that are declared without the packed modifier and fields in class structures are aligned on word boundaries.
If you select Double Word (equivalent to {$A4}), fields in record types that are declared without the packed modifier and fields in class structures are aligned on double-word boundaries.
If you select Quad Word (equivalent to {$A8} or {$A+}), fields in record types that are declared without the packed modifier and fields in class structures are aligned on quad word boundaries.
Regardless of the state of the $A directive, variables and typed constants are always aligned for optimal access. Execution is faster if you set the option to 8 (Quad Word).
This is the default.