‘auto-release pool’ type behavior in C++ with shared_ptr

With boost’s shared_ptr and standard contaniers, ‘auto-release pool’ (as seen in much Obj-C code) type structures can created in C++.


#include <boost/shared_ptr.hpp>
using boost::shared_ptr;
#include <vector>
class A{...};
typedef shared_ptr<A> A_ptr;
...
vector<A_ptr> vec_of_a;
for(int i = 0; i < 10; i++){
  A_ptr p(new A());
  vec_of_a.push_back(p);
}
...
// do stuff with vector
...
vec_of_a.clear(); //automagically calls delete on all A_ptrs in vector

To avoid having to call vector::clear(), you can make the vector itself a boost::shared_ptr or boost::scoped_ptr; this will cause the vector itself to be automatically reclaimed, along with its contents.

See Boost’s Smart Pointer Documentation for more info.