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’m 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 aboost::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.