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:
0
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