我有一个用指向对象的指针填充的向量.我正在努力学习良好的内存管理,并有一些一般性问题:
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:
new 关键字声明的变量调用 delete.如果在堆上分配了东西,则必须将其删除(释放)以防止内存泄漏.delete myVec[index].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.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.
这篇关于在删除指向动态分配对象的指针向量中的元素之前,我需要做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
std::reference_wrapper 和简单指针的区别?Difference between std::reference_wrapper and simple pointer?(std::reference_wrapper 和简单指针的区别?)
常量之间的区别.指针和引用?Difference between const. pointer and reference?(常量之间的区别.指针和引用?)
c++ - 如何从指向向量的指针访问向量的内容?How to access the contents of a vector from a pointer to the vector in C++?(c++ - 如何从指向向量的指针访问向量的内容?)
*& 的含义和**&在 C++ 中Meaning of *amp; and **amp; in C++(*amp; 的含义和**amp;在 C++ 中)
为什么我不能对普通变量进行多态?Why can#39;t I do polymorphism with normal variables?(为什么我不能对普通变量进行多态?)
取消引用已删除的指针总是会导致访问冲突?Dereferencing deleted pointers always result in an Access Violation?(取消引用已删除的指针总是会导致访问冲突?)