4

Is there a STL utility/algorithm to do delete *the_object_iterator; on all the objects? So that I can clear() safely? The STL container is a set and the objects are pointers to C++ classes created with new.

Boost seems to be the best solution. My goal was to avoid copy-construction on noncopyable classes.

unixman83
  • 9,421
  • 10
  • 68
  • 102
  • 8
    Consider using Boost.PointerContainer instead http://www.boost.org/doc/libs/1_47_0/libs/ptr_container/doc/ptr_container.html – K-ballo Sep 29 '11 at 20:25
  • See http://stackoverflow.com/questions/991335/how-to-erase-delete-pointers-to-objects-stored-in-a-vector – Dabbler Sep 29 '11 at 20:27
  • @Dabbler that's not a one-liner built-in – unixman83 Sep 29 '11 at 20:30
  • 8
    It's generally a bad idea to hold pointers in a container, because if the container is destroyed accidentally (via an exception for example) you won't get the opportunity to clean up properly. – Mark Ransom Sep 29 '11 at 20:30
  • ... to hold raw (dumb) pointers. It's OK to hold smart pointers. A common pattern, in fact. – MSalters Sep 30 '11 at 07:37
  • @MSalters Boost.PointerContainer is the best solution. Smart pointers are dumb to me. ;-) – unixman83 Oct 01 '11 at 00:06

3 Answers3

16

Use a smart pointer to hold the class pointers

std::set<std::unique_ptr<MyClass> > mySet;
Praetorian
  • 106,671
  • 19
  • 240
  • 328
10

As far as I know, there is no standard algorithm to delete all objects. However, you can build up one easily:

template< typename T > invoke_delete( T* ptr ){ delete ptr; }

std::for_each( set.begin(), set.end(), &invoke_delete< set_value_type > );
K-ballo
  • 80,396
  • 20
  • 159
  • 169
7

Boost pointer containers are the way to go.

Not only do they store the dynamically allocated objects. But the objects are accessible as references which makes using the standard algorithms on the the object that much easier.

boost::ptr_set<MyClass>   setData;

setData.insert(new MyClass);
Martin York
  • 257,169
  • 86
  • 333
  • 562