从指针的向量的向量中释放内存

Deallocating memory from a vector of vectors of pointers

本文关键字:向量 内存 释放 指针      更新时间:2023-10-16

我正在创建一个粒子物理模拟器,我需要做适当的内存管理。

我发现我的方法一次传播几个粒子很方便,所以这个方法返回一个轨迹向量,每个轨迹是一个步骤向量(因此得到一个vector< vector<> >)。

(Step是我创建的一个类)

vector< vector<Step*> > Propagator::Propagate (vector<TParticle*> vpart) {
  vector< vector<Step*> > = vvsteps;
  //vvsteps goes through physics and gets filled using push_back
  //all of vvsteps' entries were filled with objects created with "new"
  return vvsteps;
}

每个步骤创建一个指向TParticle(用new创建)的指针向量,并具有以下析构函数来释放它。

vector<TParticle*> vpart;
Step::~Step() {
  for(int i=0; i<vpart.size(); i++) delete vpart[i];
  vpart.clear();
}

当我得到我想要的东西后,我尝试通过以下操作来释放整个东西:

vector< vector<Step*> > vvstep = prop->Propagate(vpart);
/*PHYSICS GOES HERE*/
for(int i=0; i<vvstep.size(); i++) {
  for(int j=0; j<vvstep[i].size(); j++)
    delete (vvstep[i])[j];
  vvstep[i].clear();
}
vvstep.clear();

这段代码由于某些原因不能工作。它给了我以下错误

*** glibc detected *** bin/rtest.exe: double free or corruption (fasttop): 0x0f7207f0 ***

编辑:更正了一个错别字,类被命名为Step而不是Steps。

将vector类型的vector更改为:

`std::vector< std::vector<std::unique_ptr<Step>>>`

可以做一些事情。首先,它阻止复制您的std::vector,这是不好的,因为这些向量既表示所有权,也表示对数据的引用。

move仍然可用,并且通常应该出现。如果您想将向量的一组向量移动到另一个位置,并且它不会自动发生,则插入std::move( src )

其次,当数据的vectorvector超出作用域时,unique_ptr会自动清理Step对象。

你可能不得不在unique_ptr<Base>上插入一些.get()调用,当你调用一个直接接受Base*的函数时。但它应该是透明的。

请注意,可能发生双重删除是因为您复制了Base*的这些vector中的一个—当您试图这样做时,std::vector<std::unique_ptr<Base>>会报错…