C++子结构位域大小

ima*_*ett 5 c++ bit-fields

考虑以下:

class A { public:
    int     gate_type :  4;
    bool storage_elem :  1;
    uint8_t privilege :  2;
    bool      present :  1;
} __attribute__((packed));

class B { public:
    struct Sub {
        int     gate_type :  4;
        bool storage_elem :  1;
        uint8_t privilege :  2;
        bool      present :  1;
    } type_attr; //Also tried with "__attribute__((packed))" here in addition to outside
} __attribute__((packed));
Run Code Online (Sandbox Code Playgroud)

编译器是g ++ 4.8.1.sizeof(A)== 1,sizeof(B)== 4.为什么会这样?我需要像结构B这样的东西,大小为1.

Joe*_*e Z 3

这似乎是一个愚蠢的反问。当我将您的示例重写为:时,我得到了您想要的结果:

class A { public:
    int     gate_type :  4;
    bool storage_elem :  1;
    uint8_t privilege :  2;
    bool      present :  1;
} __attribute__((packed));

class B { public:
    A type_attr; //Also tried with "__attribute__((packed))" here in addition to outside
};
Run Code Online (Sandbox Code Playgroud)

是否有某种原因无法重用class Ainside of的定义class B?这似乎确实是更好的方法。

我记得,C 和 C++ 都不能保证 与struct Sub具有相同的布局和相同的存储要求class A,尽管具有相同的字段宽度、顺序等。(在 C 的情况下,它是struct Subvs. struct A,但同样的想法成立,因为这些都是 POD 类型。)

确切的行为应该依赖于 ABI。不过,通过像我上面所做的那样重用class A,我认为您可以让自己对 ABI 问题更加免疫。(稍微,不是不渗透。)