c++ - 与 C++ 中的数组相比,为什么一个类使用这么多内存

标签 c++ arrays memory

<分区>

我想存储 1000 个矩形的 3 个属性。我可以用两种不同的方式做到这一点。我可以使用结构或数组,但我试图找出哪种解决方案使用的内存最少。这里的代码:

struct Figure {
    unsigned int color;
    virtual void foo() {}
};

struct Rectangle : public Figure {
    unsigned int width,height;
};

int main() {
    Rectangle r[1000];
    unsigned int r2[1000][3]; //This take less memory, The first entry is rectangle number
                        // the next is color, width and height
std::cout<<"Type name is "<< typeid(r[0]).name() <<sizeof(r2)<<" "<<sizeof(r)<<std::endl;
return 0;
}

输出是:

类型名称是 9Rectangle12000 24000

如您所见,结构对象数组使用的内存是普通数组的两倍。为什么会这样? 由于多态结构,我预计我的情况下的结构数组会使用更多内存,但不会那么多。

最佳答案

  1. 你的结构有虚函数,所以里面有一个 vptr。

  2. 出于对齐目的,成员之间和/或结构末尾可能存在填充。

关于c++ - 与 C++ 中的数组相比,为什么一个类使用这么多内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50820810/

相关文章:

memory - 共享库是否减少了 WebSphere AppServer 7 上的内存占用?

c++ - 在 Rcpp 中为 Galerkin 矩阵使用 Eigen c++ 库的问题

c++ - 在不重新链接的情况下更新依赖于 Boost 库的库的 Boost 版本

javascript - 如何使用 lodash 从较大数组内的对象中获取数组?

javascript - 加载复杂的 .obj 文件时 AFrame/Three.js : why so many (JS)Strings in memory,?

python - 该类的两个不同实例在内存中具有相同的列表地址

c++ - 为什么 threading.stack_size() 没有产生想要的效果?

c++ - 如何检查 std::vector 的调整大小是否有适当的内存

c++ - 按升序排列数组

JavaScript forEach 循环使用 .push() 将一个数组分成其他数组