STL: calling delete on every object in a collectio

4851117d61425bafb6c034e0f595d517
0
DrunkenCoder 101 Jul 29, 2003 at 13:00

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 =)

5 Replies

Please log in or register to post a reply.

6ad5f8c742f1e8ec61000e2b0900fc76
0
davepermen 101 Jul 29, 2003 at 13:02

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

but yes, its great for container cleanup..

4851117d61425bafb6c034e0f595d517
0
DrunkenCoder 101 Jul 29, 2003 at 13:09

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.

6ad5f8c742f1e8ec61000e2b0900fc76
0
davepermen 101 Jul 29, 2003 at 13:13

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

4851117d61425bafb6c034e0f595d517
0
DrunkenCoder 101 Jul 29, 2003 at 13:18

@davepermen

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

Well you got to love M$VC++ 6.0 broken scope rules ;)

6ad5f8c742f1e8ec61000e2b0900fc76
0
davepermen 101 Jul 29, 2003 at 13:25

yeah, good old days:D