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

标签 c++ struct sizeof

<分区>

在我必须处理的包含旧代码的项目中,我有这个 Coord 结构。据我所知,它的大小应该是 12 个字节或 24 个字节。但是,sizeof(Coord 返回 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);
};

最佳答案

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

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

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

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

关于c++ - 为什么这个结构的大小看起来应该是 12/24 却为 40?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50184657/

相关文章:

java - 如何检索 PostgreSQL 列名并导入到 Matlab 中的结构数据

c++ - 为什么 C++ 中空类的大小不为零?

c++ - boost::filesystem 的段错误

c++ - 如何使用 Boost 在 C++ 中制作代理服务器

c++ - 在 C++ 中让一个类完成工作还是将一个类分成几个子类?

c - 如何在 C 中找到动态分配数组的大小?

c - sizeof(array_of_char) 输出奇怪的数字

c++ - undefined reference 错误 : `ClassName::ClassMember`

c - 结构体指针前向声明?

在C中计算结构的哈希值