Vidya
Vidya

Reputation: 8197

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?

Upvotes: 1

Views: 551

Answers (2)

Eric Z
Eric Z

Reputation: 14505

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.

Upvotes: 0

Alexey Malistov
Alexey Malistov

Reputation: 26975

Use shared_ptr

struct B {...};

struct A {
  A() : bb(new B) {} // auto-deallocate
  boost::shared_ptr<B> bb;
}

Upvotes: 1

Related Questions