Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STL algorithm to delete all the objects in a container?

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.

like image 850
unixman83 Avatar asked Nov 28 '22 04:11

unixman83


2 Answers

Use a smart pointer to hold the class pointers

std::set<std::unique_ptr<MyClass> > mySet;
like image 128
Praetorian Avatar answered Dec 16 '22 10:12

Praetorian


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 > );
like image 23
K-ballo Avatar answered Dec 16 '22 09:12

K-ballo