5

考虑以下:

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));

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

4

1 回答 1

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
};

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

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

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

于 2013-07-04T07:15:27.533 回答