Some questions in STL map and list using in c++
Hello I would like to ask about: I have map and list
Questions:
Is the following implementation of distructor right :
for (map<string,SymbolTableNode*>::iterator i = symbolTable.begin();
i != symbolTable.end(); ++i)
{
delete i;
}
symbolTable.clear();
or I miss some memory?
About list:
list<MyClass2*> mylist;
mylist.push_front(new MyClass());
mylist.pop_front();
does pop i开发者_开发知识库nvoke delete? or I have memory leakage in this case? If there is the leakage problem then what can I do to avoid it?
Thank you.
No pop_front
won't invoke delete. You'll have to delete the pointer yourself before you pop it.:
list<MyClass2*> mylist;
mylist.push_front(new MyClass());
delete mylist.front();
mylist.pop_front();
And the destructor should probably be:
delete i->second;
you have a leak. See smart pointers (http://en.wikipedia.org/wiki/Smart_pointer)
More explicitely:
list<boost::shared_ptr<MyClass2> > mylist;
mylist.pop(); // now it will invoke delete
Do you really need to have a list of pointers ? Can't you have a plain list ?
list<MyClass> mylist;
mylist.push_front(MyClass());
It will save you the pain of memory management.
If you need pointers, then use smart pointers or pointer containers from boost : http://www.boost.org/doc/libs/1_46_1/libs/ptr_container/doc/ptr_container.html
delete i;
Wrong.
This should be this:
delete i->second;
Because i
points to a pair.
Nawaz - You are wrong.
Iterator element for a map is a pair so proper delete call is:
delete (*i).second;
P.S. Ok - now I see You have fixed this :)
精彩评论