#pragma pack(n)与Memory Alignment

以下是MSDN中的话:

Structure Packing and Alignment

Structure packing interacts with compiler alignment behavior as follows.

  • If the packsize is set equal to or greater than the default alignment, the packsize is ignored.
  • If the packsize is set smaller than the default alignment, the compiler aligns according to the packsize value.

(上面两点其实意思就是:对齐边界为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:

  • The command-line option /Zp (Struct Member Alignment) sets the packsize to n, in which n can be 1, 2, 4, 8, or 16, and in which 8 is the default.
  • The compiler directive #pragma pack([n]) sets the packsize to n, in which n can be 1, 2, 4, 8, or 16. If n is not specified, #pragma pack resets the packsize to its value at the beginning of compilation: either the value specified by /Zp (Struct Member Alignment), or the default, which is 8 on most platforms.
    The pragma applies only from the point at which it occurs in the source. For example, the /Zp1 option sets the packsize to 1, which causes the compiler to use no padding within structures. To avoid this problem, turn off structure packing or use the __unaligned keyword when accessing unaligned members of such structures through pointers.

关于预处理指令:#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.

你可能感兴趣的:(windows,.net,XP,vc++)