Can my code cause a memory leak with STL Linked List?



Suppose I have the following class and I implement the following logic.

1
2
3
4
5
6
list<Dock*> myDockPtrs;
myDockPtrs.push_front(new Dock(12, 24, "MyFirstDock")); // Heap memory
myDockPtrs.push_front(new Dock(-4, -24, "MySecondDock"));

~myDockPtrs(); // Memory Leak?


See what I have done, I have allocated memory ptrs onto the list but I have failed to delete the contents. Is there any chance that the STL list is smart enough to deallocate the ptrs for me? If not, what do I need to do to deallocate them?

EDIT: Same question goes if I do a pop operation.
Last edited on
Is there any chance that the STL list is smart enough to deallocate the ptrs for me?

That would be a very silly thing for the list to do for you; it has no way of knowing when you are done with the object and it can be safely deleted.

A very simple solution is to use a shared pointer. When using a shared pointer, the object will be automatically deleted when nobody has a copy of the pointer anymore.

Something like this ought to do it.

1
2
3
list<std::shared_ptr <Dock> > myDockPtrs;
std::shared_ptr<Dock> somePointer (new Dock(12, 24, "MyFirstDock"));
myDockPtrs.push_front(somePointer);



Can shared pointers possibly be passed into functions take pointer arguments?
Last edited on
Shared pointers come with a get function that gives you a naked pointer to the object.

http://www.cplusplus.com/reference/memory/shared_ptr/get/

It's up to you to ensure that you don't delete the object and then try to use the naked pointer to access it, but that's true of every pointer and you already have to think about that.
Last edited on
Thank you!
Topic archived. No new replies allowed.