简体   繁体   中英

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.

使用智能指针来保存类指针

std::set<std::unique_ptr<MyClass> > mySet;

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM