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
内存对齐详解
本文详细介绍了C/C++中内存对齐的概念及其实现方法,包括使用#pragma pack和__declspec(align())进行结构体内存对齐的具体操作。通过实例展示了不同情况下成员变量如何按指定字节数对齐以及结构体总大小的计算。
3172

被折叠的 条评论
为什么被折叠?



