about pack and align for C/C++

http://msdn.microsoft.com/en-us/library/2e70t5y1(VS.80).aspx

 

#pragma pack(  n  )

n : 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.

The default value for  n  is 8

成员变量对齐:选n该成员长度 的 最小值(的倍数)
结构ABCD中 d的对齐方式,选n和sizeof(d)的最小值8,然后按8字节对齐!!!
sizeof大小:选n最大成 员长度 的最小值,对齐

例子:
#pragma pack(8)
struct ABCD
{
bool b;
short s;
double d;
};

int main()
{
cout << offsetof(ABCD, b) << endl;
cout << offsetof(ABCD, s) << endl;
cout << offsetof(ABCD, d) << endl;
cout << sizeof(ABCD) << endl;
}

output is:
2
8
16


__declspec( align( n ) )

__declspec( align() ) 和 #pragma pack 是一对兄弟,前者规定了对齐的最小值,后者规定了对齐的最大值,两者同时出现时,前者拥有更高的优先级。 

例子:
#define CACHE_ALIGN 64 

// Force each structure to be in a different cache line. 
struct __declspec(align(CACHE_ALIGN)) CUSTINFOAA { 
DWORD    dwCustomerID;     // Mostly read-only 
wchar_t  szName[100];      // Mostly read-only 

// Force the following members to be in a different cache line. 
__declspec(align(CACHE_ALIGN)) 
  int nBalanceDue;           // Read-write 
FILETIME ftLastOrderDate;  // Read-write 
}; 


int main()
{
cout << offsetof(CUSTINFOAA, dwCustomerID) << endl;
cout << offsetof(CUSTINFOAA, szName) << endl;
cout << offsetof(CUSTINFOAA, nBalanceDue) << endl;
cout << offsetof(CUSTINFOAA, ftLastOrderDate) << endl;
cout << sizeof(CUSTINFOAA) << endl;
}

Output:
0
4
256
260
320
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值