Re: the correct way to delete a map
Nick Keighley wrote:
On 8 Nov, 10:55, Nick Keighley <nick_keighley_nos...@hotmail.com>
wrote:
Hi,
I have a map containing pointers. When I destroy the map I want to
delete
all the pointers.
typedef std::map<std::string, const T*> Table;
void destroy_map ()
{
for (Table::iterator i = table_.begin(); i != table_.end(); ++i)
{
delete (*i).second;
table_.erase (i);
}
}
this crashes. Does the erase() invalidate the iterator?
This was the code I found on the net (latout fixed a bit)
for (map::iterator itr = myMap.begin(); itr != myMap.end())
{
if(itr->value == something)
myMap.erase(itr++);
else
itr++;
}
which it is claimed is from Josuttis. I suppose the fact that it
didn't compile should of made me doubt this...
ah! more poking around on the net. erase() does invalidate the
iterator. That's why the net code does a post increment in the erase
call.
So preumably I want:-
void destroy_map ()
{
for (Table::iterator i = table_.begin(); i != table_.end();)
{
delete (*i).second;
table_.erase (i++);
}
}
since this code is actually in a DTOR and table_ is member variable
would I be better leaving the destruction of the map to the DTOR?
It definitely would. And I'll tell you more, that if you use a smart
pointer you can also forget about the deallocation. The bad thing is
that you need to use additional libraries, such as boost.
Then you can have something as:
#include <map>
#include <boost/shared_ptr.h>
typedef boost::shared_ptr<int> ElementPtr;
typedef std::map<int, ElementPtr> Table;
int main(){
Table t;
t[1] = ElementPtr(new int(1));
t[2] = ElementPtr(new int(2));
}
this will be correctly deleted by the map destructor.
Regards,
Giuseppe