Structure packing interacts with compiler alignment behavior as follows.
(上面两点其实意思就是:对齐边界为packsize(1 2 4 8 16)和default alignment(一般为8)中的较小者。)
Thus, if the packsize is set to four, data types having a size of four, eight, or 16 bytes are aligned on addresses that are multiples of four. However, there is no guarantee that data types eight bytes in size (64 bits) are aligned on addresses that are a multiple of eight. The packsize has no effect on data types outside of a structure.
In addition, packing affects the alignment of the entire packed structure. For example, in a structure declared under #pragma pack(1), the alignment of all members are forced to one, regardless of whether they would have been naturally aligned even without packing.
The following techniques set a packsize, in bytes:
关于预处理指令:#pragma pack(n)在MSDN中针对.net framework1.1中的说法是:
Specifies the value, in bytes, to be used for packing. The default value for n is 8. Valid values are 1, 2, 4, 8, and 16. The alignment of a member will be on a boundary that is either a multiple of n or a multiple of the size of the member, whichever is smaller.
#pragma pack(16)
class MyObject{
public:
int a;
double c;
virtual ~MyObject(){}
virtual out(){}
};
在Windows Xp sp2 (32位) VC++6.0 下 MyObject对象的大小应该是:24. 这里的对齐边界应该是8 (packsize=16,default alignment=8) 存在虚函数因此会有虚函数表指针:4字节,再加上int a:4字节 但是要对齐到边界值8,double:8字节,因此加起来一共是24.