![]() |
STL and memory management
hi,
I have this question about using STL with dynamically allocated memory. say for example I do this: :
list<int *> mylist;and i do stuff on the list - i.e. create pointers to new memory and operate on it. suppose the time comes to get rid of all that memory, is it fine to use the erase method on the list? i.e. :
list<int *>::iterator start = mylist.begin();or must i iterate over the list and explicitly delete memory as i go along??? |
You must iterate over the list and delete memory as you go. From what you say, an example would be this;
:
#include <list>Unlike some other languages, C++ does not employ a garbage collector unless you deliberately find one and use it in your program. |
hey Grumpy!
thanks for the reply! I was just wondering if STL freed dynamically allocated memory... appears not! ok so now i know that any call to new must be removed by hand using delete - or by garbage collection! |
Quote:
|
yeah i already got that!
|
Unless you have the Boost Pointer Container library. The only catch here is that it manages the memory for you, so when the list it destroyed all the objects it holds are deleted. So if you are storing pointers to an object in the pointer container it will become invalid.
|
Doesn't the auto_ptr class in the standard library do the same thing?
|
Both the Boost Pointer Container Library and std::auto_ptr invoke operator delete to release dynamically allocated memory. Neither provides a means of ensuring that dynamically allocated memory pointed at by some raw pointer is automatically released.
|
What? Of course they do, that is what they are for. You give them the raw pointer and they will release the memory for you as the spec says. Of course no library is going to give you garbage collection of an arbitrary raw pointer.
Example: :
|
There is still an issue with your use of the auto_ptr, demonstrated with a slight change to your program:
:
#include <iostream>:
$ ./a.out |
| All times are GMT -5. The time now is 2:11 AM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC