1

I have a map

std::map<std::string, my_class*> name2ptr; 

I try to delete the contents of the map by first traversing through the map to delete the the my_class pointers and later clear the map. Now, I have a problem when there is only one pair in the map. The map has only one entry now

<"ajay", 0xabcd> 

It crashes at delete((*itr).second). The for loop is as below.

name_map_type::iterator itr; for( itr= name2ptr.begin();itr!=name2ptr.end();itr++){ if((*itr).second){ delete ((*itr).second); } } name2ptr.clear(); 

How can I solve this?

3
  • 3
    It's crashing there, but the problem is somewhere else. Commented Dec 20, 2012 at 5:45
  • There is nothing wrong with the code you've posted. The error is almost certainly some where else in your code. Commented Dec 20, 2012 at 5:45
  • 1
    what does the destructor for my_class look like? Commented Dec 20, 2012 at 5:49

1 Answer 1

3

Did you put a bad pointer into the map? Firstly, there is no need to check for nullptr on (*itr).second; deleteing a nullptr is perfectly OK, it won't do anything.

You should look at storing std::shared_ptr<my_class> as your map's value type instead of a raw pointer. That way, you just have to call name2ptr.clear(), and as long as nothing else is holding a reference to the object, it will be deleted.

Check out this reference.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.