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

April 6, 2009

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());
// 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.

One Response to “‘auto-release pool’ type behavior in C++ with shared_ptr”

  1. The part about making vector too a shared_ptr is nonsense. It’s allocated in the automatic store and doesn’t need to be explicitly destroyed.

Leave a Reply