It is well known that if a constructor throws, then all fully constructed sub-objects will be destroyed in reverse order including member data and all kinds of base classes. The destructor does not get called for non-delegating constructors though. For a delegating constructor the object has been constructed when the constructor body is entered, but construction continues somewhat. Therefore the question arises whether the destructor of the class is called, if the delegating constructor throws an exception from within its body?
class X
{
public:
X();
X(int) : X() { throw std::exception(); } // is ~X() implicitely called?
~X();
};
Destructors are only called for the completely constructed objects. When the constructor of an object throws an exception, the destructor for that object is not 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.
Constructor Failures by Herb Sutter 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.
Constructors are also called when local or temporary class objects are created, and destructors are called when local or temporary objects go out of scope. You can call member functions from constructors or destructors.
The rule is that the destructor is called for all fully constructed objects. The object is considered fully constructed once any constructor has finished, including the delegated constructor (even though the program continues in another constructor).
The lifetime of an object begins when any constructor (i.e., in the case of delegation, the ultimate target constructor) is successfully completed. For the purposes of [C++03] §3.8, “the constructor call has completed” means any constructor call. This means that an exception thrown from the body of a delegating constructor will cause the destructor to be invoked automatically.
source.
And here is a nice article about delegating constructors, should anybody want to read it.
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