gpt4 book ai didi

C++ 子结构位域大小

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:40:09 24 4
gpt4 key购买 nike

考虑以下几点:

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

有什么原因不能在 class B 中重用 class A 的定义吗?这似乎确实是更好的方法。

我记得,C 和 C++ 都不能保证 struct Subclass A 具有相同的布局和相同的存储要求,尽管具有相同的字段宽度,订单等等。 (在 C 的情况下,它是 struct Substruct A,但同样的想法成立,因为它们都是 POD 类型。)

确切的行为应该依赖于 ABI。不过,通过像我上面那样重用 class A,我认为您可以稍微增强对 ABI 问题的免疫力。 (有点,不是不透水。)

关于C++ 子结构位域大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17463638/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com