std :: shared_ptr比vector更多的内存空间

Muh*_*ooq 1 c++ vector shared-ptr

我有一个体素结构:

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;
    }
};
Run Code Online (Sandbox Code Playgroud)

对于体素的数量,我有一个非常大的n.

int n = 300 * 300 * 300;
Run Code Online (Sandbox Code Playgroud)

现在,当我用向量初始化体素时,RAM大约需要79 MB.

std::vector< voxel > vi(n);
Run Code Online (Sandbox Code Playgroud)

但是当我使用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()));
}
Run Code Online (Sandbox Code Playgroud)

这种行为可能是什么原因,我该如何避免呢?

补充说明:

std::vector< std::shared_ptr<voxel> > vi(n); //statement takes 211 MB alone
Run Code Online (Sandbox Code Playgroud)

更新:我也试过这个循环而不是回推,但结果是一样的.我现在有一个普遍的要点,为什么会发生这种情况.

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;
    }
Run Code Online (Sandbox Code Playgroud)

Nat*_*ica 6

std::vector< voxel > vi(n);
Run Code Online (Sandbox Code Playgroud)

是要占用sizeof(voxel) * n内存的字节数.当您更改为共享指针时,您现在将获得共享指针的成本和voxel.那将是等同的

sizeof(voxel) * n + sizeof(std::shared_ptr<voxel>) * n
Run Code Online (Sandbox Code Playgroud)

其中sizeof(std::shared_ptr<voxel>)可能是16个字节.

在你宣布的第二个例子中,你也浪费了很多空间

std::vector< std::shared_ptr<voxel> > vi(n);
Run Code Online (Sandbox Code Playgroud)

这将创建nshared_ptrs然后你push_back另一个n非空shared_ptrs,所以你doulbe矢量的大小.如果你想预先分配vector那么你应该使用的大小

std::vector< std::shared_ptr<voxel> > vi;
vi.reserve(n);
Run Code Online (Sandbox Code Playgroud)