Re: the correct way to delete a map
Nick Keighley <nick_keighley_nospam@hotmail.com> wrote:
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?
Yes. Try this instead:
void destroy_map()
{
for ( Table::iterator i = table_.begin(); i != table_.end(); ++i )
{
delete i->second;
i->second = 0; // I don't think this is strictly necessary...
}
table_.clear();
}
or if you want to have fun with algorithms:
typedef map<int, int*> Table;
template < typename T >
void delete_second( T& t ) {
delete t.second;
t.second = 0;
}
void destroy_map()
{
for_each( table_.begin(), table_.end(),
&delete_second<Table::value_type> );
table_.clear();
}