在 GCC 中使用为 类 打包的属性

Using attribute packed for classes in GCC

GCC 文档 says:

You may only specify the packed attribute attribute on the definition of an enum, struct or union, not on a typedef that does not also define the enumerated type, structure or union.

这是否意味着我不能为 类 应用此属性?

我在 GCC 文档中找不到明确的答案,但通过以下实验,似乎可以。

#include <iostream>


struct UnPackedStruct {
    unsigned char a;
    int b;
};

struct __attribute__ ((__packed__)) PackedStruct {
    unsigned char a;
    int b;
};

class __attribute__ ((__packed__)) PackedClass{
    unsigned char a;
    int b;
};

int main()
{
    std::cerr << "sizeof( UnPackedStruct ): " << sizeof(UnPackedStruct)
            << ", sizeof( PackedStruct ): " << sizeof(PackedStruct)
            << ", sizeof( PackedClass): " << sizeof(PackedClass)
            << "\n";

    return 0;
}

输出:

sizeof( UnPackedStruct ): 8, sizeof( PackedStruct ): 5, sizeof( PackedClass): 5

Try it with online compiler

documentation for GCC 9.x 已更新为在该列表中包含“class”:

You may only specify the packed attribute on the definition of an enum, struct, union, or class, not on a typedef that does not also define the enumerated type, structure, union, or class.

因此您当然可以将该属性应用于 classes,至少从 GCC 9.x 开始,但也可能在早期版本中如此。