Reputation:
Consider the following class:
struct A
{
A(){ std::cout << "A()" << std::endl; throw std::exception(); }
~A(){ std::cout << "~A()" << std::endl; }
};
A a;
int main(){ }
The Standard promised that the appropriate deallocation function will be called N4296::5.3.4/20 [expr.new]
:
If any part of the object initialization described above78 terminates by throwing an exception, storage has been obtained for the object, and a suitable deallocation function can be found, the deallocation function is called to free the memory in which the object was being constructed,
But what about destructor? In that example it was no called. So, did we get UB?
Upvotes: 0
Views: 57
Reputation: 735
Destructors are not same as deallocators. Whenever a variable goes out of scope the object referenced to the variable is deleted. In the problem you have given the object is a global variable, so it will be deleted when the program terminates.
Upvotes: 0
Reputation: 145224
Destructors are called for all successfully initialized objects.
Otherwise there would have had to be default zero-initialization (some overhead) in order to be able to assume anything in a destructor.
The A object whose constructor throws, is not successfully initialized. So its destructor is not executed. However, if it had any class type sub-objects (base class sub-objects, data members) that had been successfully initialized prior to the exception, then destructors would be called for these.
And no, throwing from a constructor is not UB.
On the contrary it's the common way of signalling construction failure, and it ensures that the caller will either have a successfully initialized and presumably useable object, or else (just) an exception.
History. Originally C++ didn't have exceptions. Construction failure was then signalled by assigning 0 to this
. I can't recall how that interacted with allocation, but presumably the same way that an exception now does, namely a guaranteed deallocation. But with this scheme you could only fail construction for dynamically allocated objects…
Upvotes: 2