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).)