Possible Duplicate:
What happens to base class destructor if a derived class destructor throws an exception
If I throw an exception in the constructor of a derived class, is the destructor called to clean up the base class?
When throwing an exception in a constructor, the memory for the object itself has already been allocated by the time the constructor is called. So, the compiler will automatically deallocate the memory occupied by the object after the exception is thrown.
However, the copy constructor for an exception object still must not throw an exception because compilers are not required to elide the copy constructor call in all situations, and common implementations of std::exception_ptr will call a copy constructor even if it can be elided from a throw expression.
Throwing an exception in a constructor can lead to partially initialized objects. As described in Guideline 7.3 of Java Secure Coding Guidelines, partially initialized objects of a non-final class are prone to a security concern known as a Finalizer Attack.
When an exception is thrown, destructors of the objects (whose scope ends with the try block) are automatically called before the catch block gets executed. That is why the above program prints “Destructing an object of Test” before “Caught 10“.
The destructors of the base class(es) are then called in the reverse order.
Before that, the destructors of any already initialized member will also get called.
However, the destructor of the currently constructed derived-class won't get called, as this part of the object will not have been really constructed yet.
Yes. For example, consider:
#include <iostream>
class B
{
public:
B() { std::cout << "B()\n"; }
~B() { std::cout << "~B()\n"; }
};
class D : public B
{
public:
D() { std::cout << "D()\n"; throw 23; }
~D() { std::cout << "~D()\n"; }
};
int main()
try
{
D d;
return 0;
}
catch(...) {}
Output:
B()
D()
~B()
http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.10
Every data member inside your object should clean up its own mess.
If a constructor throws an exception, the object's destructor is not run. If your object has already done something that needs to be undone (such as allocating some memory, opening a file, or locking a semaphore), this "stuff that needs to be undone" must be remembered by a data member inside the object.
Base destructors are guaranteed to be called, but not the destructor of the object itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With