#pragma pack(n)与Memory Alignment

本文详细解析了在C++中结构体的对齐与打包机制,包括如何通过编译器选项和预处理指令设置对齐边界,以及这些设置如何影响结构体成员的对齐方式。文中还给出了一段具体的代码示例,展示了不同设置下结构体大小的变化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以下是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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值