我有一个用指向对象的指针填充的向量.我正在努力学习良好的内存管理,并有一些一般性问题:
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模板网!