What do I need to do before deleting elements in a vector of pointers to dynamically allocated objects?(在删除指向动态分配对象的指针向量中的元素之前,我需要做什么?)
问题描述
我有一个用指向对象的指针填充的向量.我正在努力学习良好的内存管理,并有一些一般性问题:
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:
- 当我处理完向量后,我必须遍历它并对每个指针调用 delete 是真的吗?
- 为什么我不必在没有 new 语句的情况下对向量或我声明的任何其他变量调用 delete,但必须对指针调用 delete?
- 如果向量是在返回的函数中声明的(导致向量超出范围),C++ 是否会为我处理释放指针的内存?
推荐答案
- 是的
- 向量是使用模板内存分配器实现的,它们为您负责内存管理,因此它们有些特殊.但作为一般经验法则,由于堆栈和堆分配之间的差异,您不必对未使用
new
关键字声明的变量调用delete
.如果在堆上分配了东西,则必须将其删除(释放)以防止内存泄漏. - 没有.在遍历所有元素时,您必须明确调用
delete myVec[index]
.
- Yes
- 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 thenew
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. - 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.
这篇关于在删除指向动态分配对象的指针向量中的元素之前,我需要做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在删除指向动态分配对象的指针向量中的元素之


基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01