Jump to content


STL: calling delete on every object in a collectio


5 replies to this topic

#1 DrunkenCoder

    Member

  • Members
  • PipPip
  • 97 posts

Posted 29 July 2003 - 01:00 PM

How often have you written some thing like this:
for( ContainerType::iterator itr = c.begin(); itr != c.end(); ++itr)
{
  delete *itr;
}

shouldn't there be a easier more explicit way? of course there is,
using std::for_each and a simple functor we get this:

//some_header.h
struct delete_object
{
  template <typename T>
  void operator()(T *ptr){ delete ptr;}
};

//later in the code...
std::for_each( c.begin(), c.end(), delete_object());

ahhh, doesn't that feel nice? less to type extra clarity *and* it could actually
give you a speed gain becuase c.end() isn't recalculated oh and that it's less
error prone is just an added bonus =)

#2 davepermen

    Senior Member

  • Members
  • PipPipPipPip
  • 1306 posts

Posted 29 July 2003 - 01:02 PM

and never forget, boost::checked_delete or boost::checked_deleter (spelling..) does exactly that.. :D

but yes, its great for container cleanup..
davepermen.net
-Loving a Person is having the wish to see this Person happy, no matter what that means to yourself.
-No matter what it means to myself....

#3 DrunkenCoder

    Member

  • Members
  • PipPip
  • 97 posts

Posted 29 July 2003 - 01:09 PM

I hadn't had the pleasure to use boost much but I really should have a look at it one of theese days.

For a "safe delete" you could use this
struct safe_delete
{
template <typename T>
void operator()(T*& p)
{
 if( p)
 {
  delete p;
  p = 0;
 }
};

strictly speaking you should actually never need to test p against NULL because according to the standard delete NULL is safe (as is free(NULL); ) but some compilers on small platforms are known to get this wrong and do funny things
when trying to delete a NULL pointer.

#4 davepermen

    Senior Member

  • Members
  • PipPipPipPip
  • 1306 posts

Posted 29 July 2003 - 01:13 PM

yep, its useless, the if(p) delete p. but on stupid compilers useless stuff gets quite important sometimes:D

like #define for if(0) {} else for

and similar stuff:D
davepermen.net
-Loving a Person is having the wish to see this Person happy, no matter what that means to yourself.
-No matter what it means to myself....

#5 DrunkenCoder

    Member

  • Members
  • PipPip
  • 97 posts

Posted 29 July 2003 - 01:18 PM

davepermen said:

like #define for if(0) {} else for
Well you got to love M$VC++ 6.0 broken scope rules ;)

#6 davepermen

    Senior Member

  • Members
  • PipPipPipPip
  • 1306 posts

Posted 29 July 2003 - 01:25 PM

yeah, good old days:D
davepermen.net
-Loving a Person is having the wish to see this Person happy, no matter what that means to yourself.
-No matter what it means to myself....





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users