Question

I came across this fringe question that I would normally dismiss with "don't do that", but I couldn't find a satisfactory answer in the standard and would appreciate if someone could point out the reasoning:

Suppose a I have a class that throws an exception in the destructor:

struct Foo { ~Foo() { throw std::runtime_error("Catch this!"); } };

What happens to the dynamically allocated memory if I delete a dynamically allocated instance of this class?

auto p = new Foo;

try { delete p; }
catch (std::exception const &) { }

Is the deallocation function called or not? And why? Could I make this code correct by adding operator delete(p); into the catch block?

I ran a small test with GCC which seems to not deallocate the memory automatically. (Contrast this with exceptions in the constructor, in which case the deallocation function is guaranteed to be called (if it exists).)

Was it helpful?

Solution

The Standard says (5.3.5p7):

If the value of the operand of the delete-expression is not a null pointer value, the delete-expression will call a deallocation function. Otherwise, it is unspecified whether the deallocation function will be called. [ Note: The deallocation function is called regardless of whether the destructor for the object or some element of the array throws an exception. — end note ]

The note answers your question.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top