加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C子结构位域大小

发布时间:2020-12-16 05:05:20 所属栏目:百科 来源:网络整理
导读:考虑以下: 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 p
考虑以下:
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. sizeof(A)== 1,sizeof(B)== 4.为什么会这样?我需要像结构B这样的东西,大小为1.

解决方法

这似乎是一个愚蠢的反问题.当我重写你的例子时,我得到你想要的结果:
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
};

是否有某些原因你不能在B类中重复使用A类的定义?这似乎是更好的方法.

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

确切的行为应该是ABI依赖的.不过,通过重复使用上面的A类,我认为你可以让自己对ABI问题有更多的免疫力. (稍微不是不透水的.)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读