how to deallocate memory in C++
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?
Use shared_ptr
struct B {...};
struct A {
A() : bb(new B) {} // auto-deallocate
boost::shared_ptr<B> bb;
}
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.
精彩评论