开发者

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.

开发者_C百科

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


Use a smart pointer to hold the class pointers

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜