我有一个体素结构:
struct voxel
{
unsigned char R, G, B;
voxel()
{
R = G = B = 0;
}
//parameteric contructor with parameters
voxel(unsigned char pR, unsigned char pG, unsigned char pB)
{
R = pR; G = pG; B = pB;
}
};
我有一个非常大的体素数 n。
int n = 300 * 300 * 300;
现在,当我用 vector 初始化体素时,它需要大约 79 MB 的 RAM。
std::vector< voxel > vi(n);
但是当我使用 shared_ptr 和堆栈溢出以这种方式初始化它时,它需要超过 2 GB。
std::vector< std::shared_ptr<voxel> > vi(n);
for (size_t i = 0; i < n; i++)
{
vi.push_back(std::shared_ptr<voxel>(new voxel()));
}
这种行为的原因是什么?我该如何避免?
附加说明:
std::vector< std::shared_ptr<voxel> > vi(n); //statement takes 211 MB alone
更新: 我也尝试过使用这个循环而不是推回,但结果是一样的。我现在大致了解了为什么会发生这种情况。
for (size_t i = 0; i < n; i++)
{
vi[i].reset(new voxel());
vi[i]->B = 0;
vi[i]->R = 0;
vi[i]->G = 0;
}
最佳答案
std::vector< voxel > vi(n);
即将占用sizeof(voxel) * n
字节的内存。当您更改为共享指针时,您现在将拥有共享指针和 voxel
的成本。 .这相当于
sizeof(voxel) * n + sizeof(std::shared_ptr<voxel>) * n
哪里sizeof(std::shared_ptr<voxel>)
很可能是 16 个字节。
在声明时,您在第二个示例中也浪费了很多空间
std::vector< std::shared_ptr<voxel> > vi(n);
这将创建 n
空 shared_ptr
然后是你push_back
另一个 n
非空 shared_ptr
s 所以你加倍 vector 的大小。如果要预分配 vector
的大小那么你应该使用
std::vector< std::shared_ptr<voxel> > vi;
vi.reserve(n);
关于c++ - std::shared_ptr 比 vector 占用更多的内存空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33213611/