gpt4 book ai didi

C++ sizeof 自定义类返回不正确的值?

转载 作者:太空狗 更新时间:2023-10-29 21:03:31 25 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
Why isn’t sizeof for a struct equal to the sum of sizeof of each member?

给定以下类,没有其他数据成员:

typedef uint32_t id_t;
typedef int64_t loc_t;

class foo:
{
public:
enum bar : uint8_t
{
BAR1,
BAR2,
BAR3
};
private:
id_t id;
loc_t start;
loc_t stop;
bar std;
};

谁能解释一下原因:

sizeof( id_t ) returns 4...
sizeof( loc_t ) returns 8...
sizeof( bar ) returns 1...

4+(2*8)+1 = 21

然而:

sizeof( foo ) returns 32?

删除 bar 枚举类型的 uint8_t 要求只会成功地使 sizeof( bar ) 返回 4 (int),而 sizeof( foo ) 仍然返回 32,而 24 将正确字节对齐。

编辑:原因已得到令人满意的回答。我感谢所有发表评论的人,因为每个人都提出了一组不同的细节。

我需要的修复是能够使用 sizeof() 创建文件位置偏移量。因此,当我以二进制格式将 foo 写入文件时,如果稍后获得它的位置,我可以找到紧随其后的位置。如果我找到一个优雅的解决方案,我会在这里更新。

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