gpt4 book ai didi

c++ - 有没有办法没有 union "over-compensate"对齐?

转载 作者:行者123 更新时间:2023-12-03 07:15:30 25 4
gpt4 key购买 nike

我有一个看起来像这样的结构:

class Foo {
union {
size_t cap;
char buff[15];
};
bool isHeap;
};
我要 sizeof(Foo)等于 16 , 但是 sizeof(Foo)24在 64 位计算机上。我想这是因为 size_t强制 union 对齐为 8 ,因此有 1buff 之后浪费的字节和 7isHeap 之后.我想到了这个解决方案:
class Foo {
union{
struct {
size_t cap;
char ignore[7];
bool isHeap1;
};
struct {
char buff[15];
bool isHeap2
};
};
};
但它依赖于未定义的行为,因为您不知道是否要检查 isHeap1isHeap2直到您已经访问了它们的值之一。

有没有办法不浪费那些不依赖于未定义行为的字节?

作为旁注,我想不出这个问题的真正好名字,如果有人能做得更好,那就太好了。如果有人建议一个更好的名字,或者你们都认为它已经是一个合理的名字,我会删除这个评论。

最佳答案

    struct {
size_t cap;
char ignore[7];
bool isHeap1;
};

C++ 没有匿名结构。这在 C++ 中格式不正确。

But it relies on undefined behavior as you don't know whether to check isHeap1 or isHeap2 until you have already accessed one of their values.


如果成员的顺序是灵活的,那么这将是一个定义明确的替代方案:
union {
struct {
bool isHeap;
size_t cap;
} s1;
struct {
bool isHeap;
char buff[15];
} s2;
};
这是允许访问 union 的非事件成员的特殊情况:两个标准布局结构的公共(public)初始序列。换句话说,即使 s1是活跃成员(member),阅读 s2.isHeap定义明确,结果为 s1.isHeap反之亦然。

关于c++ - 有没有办法没有 union "over-compensate"对齐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64584593/

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