What do I need to do before deleting elements in a vector of pointers to dynamically allocated objects?

后端 未结 5 771
天涯浪人
天涯浪人 2020-11-30 06:35

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. Is it true that when I am
5条回答
  •  萌比男神i
    2020-11-30 07:27

    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.

    Ex:

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

    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.

提交回复
热议问题