Im having some problems to handle constructor exception in derived classes. When the derived class constructor throws an error, but the parent class has allocated some objects. Will the parent class destructor be called?
Example:
class A
{
A() { /* Allocate some stuff */ };
virtual ~A() { /* Deallocate stuff */ };
};
class B : public A
{
B()
{
/* Do some allocations */
...
/* Something bad happened here */
if (somethingBadHappened)
{
/* Deallocate B Stuff */
...
/* Throws the error */
throw Error; /* Will A destructor be called? I know B destructor won't */
};
};
~B() { /* Deallocate B Stuff */ };
}
And i was wondering if it is a good idea to do the following:
B()
{
/* Do some allocations */
...
/* Something bad happened here */
if (somethingBadHappened)
{
/* Deallocate B Stuff */
this->~B();
/* Throws the error */
throw Error; /* Will A destructor be called? I know B destructor won't */
};
};
If not, whats is a decent way to do such things?
An exception will cause the stack to unwind to a point where the exception is properly caught. This means that any objects created in the scope prior to where the exception is thrown will be destructed, including base class objects as in this example.
Try this:
Output should be: (note
B::~B()is not called)Calling the destructor manually as you’ve shown in your question will be safe as long as you don’t try to free resources that you’ve not yet allocated. Better to wrap those resources in some type of
RAIIcontainer (std::auto_ptr,boost::shared_ptr, etc.)to avoid the necessity of calling the destructor.Mooing Duck has provided a very nice illustration of how the stack unwinding works when an exception is thrown in a constructor: