C++中的#pragma pack效果

先说pragma,参考msdn,

A "pragma" instructs the compiler to perform a particular action at compile time. Pragmas vary from compiler to compiler.

再来说pragma pack这个制定字节对其的指令,如果制定了字节对齐,那么编译器将按照指定好的指令来生成代码,对性能将会造成一定影响。编译器的默认优化,有点空间换取时间的感觉。。

#pragma pack instructs the compiler to pack structure members with particular alignment. Most compilers, when you declare a struct, will insert padding between members to ensure that they are aligned to appropriate addresses in memory (usually a multiple of the type's size). This avoids the performance penalty (or outright error) on some architectures associated with accessing variables that are not aligned properly. For example, given 4-byte integers and the following struct:

structTest{
    char one;
    int two;
    char three;
};

 

The compiler could choose to lay the struct out in memory like this:

 Bytes: |  1  |  2  3  4  |  5  6  7  8  |  9    |  10 11 12  |
Member: | one |  padding  |  two         | three |  padding   |
 

and sizeof(Test) would be 12, even though it only contains 6 bytes of data. The most common use case for the #pragma (to my knowledge) is when working with hardware devices where you need to ensure that the compiler does not insert padding into the data and each member follows the previous one. With #pragma pack(1), the struct above would be laid out like this:

 Bytes: |  1  |  2  3  4  5  |  6      |
Member: | one |  two         |  three  |
And sizeof(Test) would be 6.

也就是说,如果指定了pragma pack(n),那么每个数据成员的对齐方式为其默认对齐字节数与n的最小值,而整个结构体的对齐方式取其最大数据成员的字节数和n的最小值

转载于:https://www.cnblogs.com/imageoneday/p/3521740.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值