tags:

views:

90

answers:

2

I have a class A where I construct an object of class B named bb. After constructing the object bb, I run in to a exception in Class A code which is caught by an exception handler. Now my question is how to deallocate the memory of object B in the exception handler?

+1  A: 

Use shared_ptr

struct B {...};

struct A {
  A() : bb(new B) {} // auto-deallocate
  boost::shared_ptr<B> bb;
}
Alexey Malistov
Using `boost::make_shared` instead of `new` is even more exception safe (not perhaps in this example), use less memory, and is a tad faster.
dalle
A: 

If the class B object is the member object of class A(aggregate pattern), then you don't even need deallocate it explicitly as long as B itself is RAII-ed. On the other hand, if it's a heap object( A dynamically allocates bb on heap), you need explicitly release it. You can either use boost::scoped_ptr or boost::shared_ptr(depending on whether you want bb's ownship to be shared with others) to hold the ownship of object bb so that it'll get released automatically when class A object is deleted.

Eric