Search code examples
c++pointersvectordelete-operator

Why delete in vector of instances subsitution?


This is not a practical question but it is only for educational curiosity.

In some forum I've just found this piece of code:

std::vector<MyClass*> myvec;
for(unsigned int i = 0; i < 100; ++i) {
  myvec.push_back(new MyClass( foo1 ));
}

// somewhere in the code inside a particular if statement
MyClass* replacement = new MyClass( foo2 );
delete myvec[0];
myvec[0] = replacement;

I have a vector of instances of MyClass and somewhere in the code I have to do substitution of some instances with others.

Why do I have to call the delete? Is replacing the pointer not enough?

WHAT I'VE LEARNED:


Solution

  • A standard container of pointers will never delete the target of any pointers that it contains. It has no way of knowing that they point to objects created with new - they could have been created with new[] (in which case delete[] is needed), or they could be pointers to static or automatic objects, which must not be deleted, or there may be something else responsible for deleting them.

    Usually, you would store objects in a container, rather than pointers. If you really need pointers (perhaps because the objects need to be different types), and you really need those pointers to manage the object lifetime, consider using a smart pointer such as std::unique_ptr, which automatically deletes its target, or boost::ptr_vector if that is not available.

    Otherwise, if you really must use raw pointers to manage object lifetimes, you'll have to be careful to use delete yourself at the right time. In that case, a tool such as Valgrind can help to identify the inevitable memory leaks.