Clicky


I have a map like below:

I want to know how to delete the objects from the map in the destructor.  I believe just calling erase( ) is not enough and I need to delete the objects.  How?  Thank you.
 class MyClass { typedef map<int, IParser *> ParserMap_t; typedef ParserMap_t::iterator ParserMapIter_t;     private:    static ParserMap_t _theMap; }    MyClass::MyClass {   _parserMap.insert(1, new ParserOne());   _parserMap.insert(2, new ParserTwo());   _parserMap.insert(3, new ParserThree()); }  MyClass::~MyClass {     for(ParserMapIter_t iter = _parserMap.begin(); iter != _parserMap.end(); ++iter)    {        _parserMap.erase(iter);        // delete the Parser objects??         }  }                             
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 

Select allOpen in new window

asked 12/16/2011 03:21

ambuli's gravatar image

ambuli ♦♦


5 Answers:
You are right, since you're using 'new', you need a corresponding 'delete', i.e.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
MyClass::~MyClass
{
    for(ParserMapIter_t iter = _parserMap.begin(); iter != _parserMap.end(); ++iter)
   {
       // delete the Parser objects:
       delete *iter;
       _parserMap.erase(iter);    
   }

}
link

answered

jkr's gravatar image

jkr

Thank you.  I think I cannot do
 delete *iter;
_parserMap.erase(iter);  
as erase would invalidate the iterator. right?
link

answered 2011-12-16 at 11:31:29

ambuli's gravatar image

ambuli

I think I have to do

delete iter->secondl;
_parserMap.erase(iter);
link

answered 2011-12-16 at 11:37:32

ambuli's gravatar image

ambuli

Yes, indeed, thus the order in the above. Well, you could
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
MyClass::~MyClass
{
    for(ParserMapIter_t iter = _parserMap.begin(); iter != _parserMap.end(); ++iter)
   {
       // delete the Parser objects:
       IParser*p = *iter;
       _parserMap.erase(iter);    
       delete p;
   }

}

but that's not really an optimization...
link

answered 2011-12-16 at 11:44:38

jkr's gravatar image

jkr

Oooops, sorry, yes - my bad...
link

answered 2011-12-16 at 11:45:07

jkr's gravatar image

jkr

Your answer
[hide preview]

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Tags:

×36
×1

Asked: 12/16/2011 03:21

Seen: 321 times

Last updated: 12/16/2011 03:37