从指针的向量的向量中释放内存
Deallocating memory from a vector of vectors of pointers
我正在创建一个粒子物理模拟器,我需要做适当的内存管理。
我发现我的方法一次传播几个粒子很方便,所以这个方法返回一个轨迹向量,每个轨迹是一个步骤向量(因此得到一个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 )
。
其次,当数据的vector
或vector
超出作用域时,unique_ptr
会自动清理Step
对象。
你可能不得不在unique_ptr<Base>
上插入一些.get()
调用,当你调用一个直接接受Base*
的函数时。但它应该是透明的。
请注意,可能发生双重删除是因为您复制了Base*
的这些vector
中的一个—当您试图这样做时,std::vector<std::unique_ptr<Base>>
会报错…
相关文章:
- 迭代时从向量和内存中删除对象
- 我在二维向量中是否正确分配了内存
- 字符串共享内存映射的向量
- 具有 STL 向量类型成员的类的复制内存
- 重新分配向量时,向量中的内存会发生什么情况
- 向量的内存位置不连续
- 自己的自定义向量类. 内存重新分配
- 分配具有 2D 向量大小的变量的内存
- 在统一内存 CUDA C/C++ 中分配 2D 向量
- 将 c++ 向量转换为字符 ** 而不会泄漏内存
- 大向量和内存守恒c++
- 如果不初始化结构中的向量,它会自动为空还是具有随机内存位置的值?
- 从函数内对象的向量中释放内存
- C++ 使用数组初始化时的 STL 向量内存管理
- 向量:内存处的范围错误
- 指向对象的指针向量 - 内存泄漏
- 向量内存问题
- c++向量内存不足
- 从复制构造函数外部修改对象成员时导致向量内存损坏,但从复制构造函数内部修改时不会
- 可以使用std::vector capacity/size/rereserve手动管理向量内存分配吗