Reputation: 23620
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();
};
Upvotes: 19
Views: 1705
Reputation: 9097
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.
And here is a nice article about delegating constructors, should anybody want to read it.
Upvotes: 7
Reputation: 153929
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).
Upvotes: 16