MSVC 2008 16字节结构成员对齐奇怪



谁能解释一下这是怎么回事?

我的MSVC 2008项目的结构成员对齐设置被设置为16字节 (/Zp16)对齐,然而以下结构中的一个被16字节对齐,另一个只被8字节对齐…为什么? ! !

struct HashData
{
    void *pData;
    const char* pName;
    int crc;
    bool bModified;
}; // sizeof (HashData) == 4 + 4 + 4 + 1 + padding = 16 bytes, ok
class StringHash
{
    HashData data[1024];
    int mask;
    int size;
}; // sizeof(StringHash) == 1024 * 16 + 4 + 4 + 0 = 16392 bytes, why not 16400 bytes?

这看起来可能没什么大不了的,但对我来说这是一个大问题,因为我被迫在GCC中模拟MSVC结构对齐,并指定aligned(16)属性使sizeof (StringHash) == 16400!

请告诉我,何时以及为什么MSVC覆盖/Zp16设置,我绝对无法理解…

我想你误解了/Zp16选项。

MSDN说,

当您指定此选项时,第一个之后的每个结构成员都是存储在成员类型的大小或n字节边界上

请读"以小者为准"。它没有说结构体将被16填充。它从第一个成员开始,定义了每个成员相对于彼此的边界。

你需要的是align (c++)属性,它表示

使用__declspec(align(#))精确控制用户定义数据的对齐

那么试试这个:

_declspec(align(16)) struct StringHash
{
    HashData data[1024];
    int mask;
    int size;
}; 
std::cout << sizeof(StringHash) << std::endl;

它应该输出你期望的内容。

或者你可以使用#pragma pack(16)

考虑使用pack pragma指令:

// Set packing to 16 byte alignment
#pragma pack(16)
struct HashData
{
    void *pData;
    const char* pName;
    int crc;
    bool bModified;
};
class StringHash
{
    HashData data[1024];
    int mask;
    int size;
};
// Restore default packing
#pragma pack()

参见:pack和Working with Packing Structures

最新更新