在向动态分配对象的指针向量中删除元素之前,我需要做什么? [英] What do I need to do before deleting elements in a vector of pointers to dynamically allocated objects?

查看:209
本文介绍了在向动态分配对象的指针向量中删除元素之前,我需要做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个向量,我用对象的指针填充。我试图学习良好的内存管理,并有几个一般问题:

I have a vector that I fill with pointers to objects. I am trying to learn good memory management, and have a few general questions:


  1. 这是真的,当我完成了矢量,

  2. 为什么我不必在向量或任何其他变量上调用delete而不使用新语句,但delete必须是

  3. 如果向量在函数中声明返回(导致向量超出范围),C ++是否会为我释放指针的内存?


推荐答案



  1. 实现使用模板内存分配器,为您处理内存管理,所以他们有点特别。但是,作为一般的经验法则,您不必在未使用 new delete c>关键字,因为堆栈和堆分配之间的区别。如果在堆上分配了内容,则必须将其删除(释放)以防止内存泄漏。

  2. 否。您必须在遍历所有元素时调用 delete myVec [index]

  1. Yes
  2. Vectors are implemented using template memory allocators that take care of the memory management for you, so they are somewhat special. But as a general rule of thumb, you don't have to call delete on variables that aren't declared with the new keyword because of the difference between stack and heap allocation. If stuff is allocated on the heap, it must be deleted (freed) to prevent memory leaks.
  3. No. You explicitly have to call delete myVec[index] as you iterate over all elements.

例如:

for(int i = 0; i < myVec.size(); ++i)
   delete myVec[i];

这样说,如果你打算在向量中存储指针, a href =http://www.boost.org/doc/libs/1_44_0/libs/ptr_container/doc/ptr_vector.html> boost :: ptr_vector 自动处理删除。

With that said, if you're planning on storing pointers in a vector, I strongly suggest using boost::ptr_vector which automatically takes care of the deletion.

这篇关于在向动态分配对象的指针向量中删除元素之前,我需要做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆