Why is this vector iterator not incrementable?

前端 未结 8 1234
没有蜡笔的小新
没有蜡笔的小新 2020-12-13 10:41

I\'m trying to delete the vector\'s content and I\'m getting an error - vector iterator is not incrementable, why is that?

This is my destructor:

C         


        
8条回答
  •  暖寄归人
    2020-12-13 11:06

    This code leaks all the contents of the vector - you have to delete *deleteIterator in the loop too. You can avoid all of this by using Base instead of Base* as the vector contents, then clear() will destruct them for you. Or use boost::ptr_vector which automates destruction if you do need raw pointers.

    Calling erase() in a forward iteration like this can be very costly if the vector is large, as every element above the current position has to be moved down to ensure elements remain contiguous. Avoid manual erase of the type you propose, for this and other reasons.

提交回复
热议问题