Advertisement

Newbie STL question

Started by May 27, 2001 12:50 AM
3 comments, last by Anthracks 23 years, 8 months ago
I''m making my first foray into the STL, and I have a quick question about the list template (well all the templates really). Basically, do I need to call an erase member function on them before quitting my app, or will the class''s destructor handle that for me? I noticed that list, for example, has clear() which wipes out everything in the linked list, but do I have to call this when I''m exiting, or is that just for convenience if I want to clear out the list during execution? Thanks, Anthracks
Not being really familiar with the STL myself, I risk telling you the wrong thing, but common sense suggests that the destructor will destroy any memory associated with the list. Therefore, you should not need to call clear() or whatever yourself when your program exits.


War Worlds - A 3D Real-Time Strategy game in development.
Advertisement
That is correct, a container will destroy all contained elements. However, be very careful: if you are storing pointers in your list that have been dynamically allocated, you have to free that memory yourself.

This is typical of one of my apps:
  MyClass{  //...  list<SomeType*> m_stList;  //...};////..later in program..//m_stList.push_back (new SomeType); // dynamically allocate objects in list////..and in cleanup..//MyClass::~MyClass (){  for (   list<SomeType*>::iterator it = m_stList.begin ()       ;  it != m_stList.end ()       ;  ++it)    delete *it; // delete each element, but don''t remove from list} // destructor automatically destroys list contents here  

Hope that''s clear. BTW, my funky ''for'' formatting is so that the auto-indenting looks decent in MSVC. Also BTW, there''s a more elegant way to do those deletes at the end using functors and "for_each", but that''s hardly a beginner topic. =)

is there a way to iterator through a container with a function with a parameter..

like with generate..

but then generate cant take a parameter..

   int zero() { return 0; } void myfunc(){ std::vector<int> abc;  generate(abc.begin(),abc.end(),zero());}    


is there a way to send in a parameter ???

{ Stating the obvious never helped any situation !! }
It appears I misspoke: for_each cannot alter the contained elements, so you can''t use it to delete everything. Bummer. Anybody know where this comes from?

jwalker: Can''t you construct the functor with arguments? I don''t know if that will accomplish what you want because I don''t know what you''re trying to do.

This topic is closed to new replies.

Advertisement