In C++, if a constructor throws an exception, what destructors are run?
In particular, does it make any difference if the exception is during the initialization list or the body?
Also, what about inheritance and members? Presumably all completed constructions get destructed. If only some members are constructed, do only those get destructed? If there is multiple inheritance, do all completed constructors get destructed? Does virtual inheritance change anything?
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.
C++ : Yes and No. While an object destructor won't be called if its constructor throws (the object "never existed"), the destructors of its internal objects could be called.
Yes, destructors are guaranteed to be called on stack unwinding, including unwinding due to exception being thrown. There are only few tricks with exceptions that you have to remember: Destructor of the class is not called if exception is thrown in its constructor.
You can throw an exception in a destructor, but that exception must not leave the destructor; if a destructor exits by emitting an exception, all kinds of bad things are likely to happen because the basic rules of the standard library and the language itself will be violated.
if a constructor throws an exception, what destructors are run?
Destructors of all the objects completely created in that scope.
Does it make any difference if the exception is during the initialization list or the body?
All completed objects will be destructed.
If constructor was never completely called object was never constructed and hence cannot be destructed.
what about inheritance and members? Presumably all completed constructions get destructed. If only some members are constructed, do only those get destructed? If there is multiple inheritance, do all completed constructors get destructed? Does virtual inheritance change anything?
All completed constructions do get destructed. Yes, only the completely created objects get destructed.
Good Read:
Constructor Failures by Herb Sutter
Especially, love the part where he explains:
In biological terms, conception took place -- the constructor began --, but despite best efforts it was followed by a miscarriage -- the constructor never ran to term(ination).
Incidentally, this is why a destructor will never be called if the constructor didn't succeed -- there's nothing to destroy. "It cannot die, for it never lived." Note that this makes the phrase "an object whose constructor threw an exception" really an oxymoron. Such a thing is even less than an ex-object... it never lived, never was, never breathed its first.
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