在删除指向动态分配对象的指针向量中的元素之前,我需要做什么?

我有一个用指向对象的指针填充的向量.我正在努力学习良好的内存管理,并有一些一般性问题:

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. 当我处理完向量后,我必须遍历它并对每个指针调用 delete 是真的吗?
  2. 为什么我不必在没有 new 语句的情况下对向量或我声明的任何其他变量调用 delete,但必须对指针调用 delete?
  3. 如果向量是在返回的函数中声明的(导致向量超出范围),C++ 是否会为我处理释放指针的内存?

推荐答案

  1. 是的
  2. 向量是使用模板内存分配器实现的,它们为您负责内存管理,因此它们有些特殊.但作为一般经验法则,由于堆栈和堆分配之间的差异,您不必对未使用 new 关键字声明的变量调用 delete.如果在堆上分配了东西,则必须将其删除(释放)以防止内存泄漏.
  3. 没有.在遍历所有元素时,您必须明确调用 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];

话虽如此,如果您打算将指针存储在向量中,我强烈建议使用 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.

相关文章