为什么这个结构的大小看起来应该是 12/24 却为 40?

Why is the size of this struct 40 when it seems like it should be 12/24?

在我必须处理的包含旧代码的项目中,我有这个 Coord 结构。据我所知,它的大小应该是 12 字节或 24。但是,sizeof(Coord returns 40。有人可以解释一下这个额外的大小是从哪里来的吗?

struct Coord
{
    Coord();
    float inate[3] = {0,0,0};
    float& x = inate[0];
    float& y = inate[1];
    float& z = inate[2];
    Coord operator*(const float&);
    Coord operator=(const Coord&);
    Coord operator=(const float[3]);
    Coord dot(const Coord& c);
    Coord cross(const Coord& c);
};

pointers/references 在您的机器上的大小可能是 8 个字节。所以 Coord 为 float 数组使用 12 个字节,为三个引用使用 24 个字节,所以结构本身需要 36 个字节。剩余的 4 个字节是由于填充以在字边界上对齐指针。

如何在不产生指针成本的情况下定义等效结构?您可以使用联合:

struct Coord
{
    union {
        float inate[3] = {0,0,0};
        float x, y, z;
    };
};

对于这个版本的 Coord,sizeof 是 12。

引用是指针。根据内存模型(32 位、64 位),引用将需要 4 个字节或 8 个字节。一个 64 位模型,将在 8 字节边界上对齐数据,这意味着在 inate[2] 和参考 x 之间填充 4 字节。

因此,对于 32 位,您将得到 4 字节 x 3 + 4 字节 x 3 = 24 字节;在 64 位模型中,你得到 4 字节 x 3 + 4 字节用于填充 + 8 字节 x 3 = 12 + 4 + 24 = 40 字节。