Deleting dynamically allocated memory from a map
I've got a map of dynamically allocated object and was wondering what the best way of deleting them was?
I was thinking maybe an interator? Something like:
studentlist::const_iterator deletemem = studentmap.begin();
for(studentlist::const_iterator deletemem=studentmap.begin(); deletemem!=studentmap.end();++deletemem)
{
Record *z=deletemem->second // Record is the type of object stored in the map student map
delete z;
}
But i'开发者_如何学Pythonm not sure, any help would be much appreciated!
Your code looks fine. However, manually deleting is probably not exception-safe. You might consider using share_ptr
(either the one from Boost, or, if you use C++0x, the standard implementation) for the values or using a boost::ptr_map
.
Edit: To delete the actual data in the map, call studentmap.clear()
after deleting all the contents. This will remove all elements from the map.
Edit 2: The problem with your solution arises when, for instance due to an exception, your cleanup code does not get called. In that case you leak memory. To overcome this problem, you can employ the RAII-idiom. Two possible ways of doing this are described above.
A better solution would be to encapsulate your dynamically allocated memory inside another object which is stack allocated. This could either be one of your own invention or you could use the shared_ptr
class from the new C++ standard or from boost.
Your code should work, but you should clear the studentmap
at the end.
Of course, you have also to invalidate any other object that should hold a copy of the pointers you are deallocating, otherwise your application will probably crash.
精彩评论