Suppose I have a pointer to a dynamically allocated array of 10 elements:
T* p = new T[10];
Later, I want to release that array:
Never do that. If there is already an active exception, std::terminate
will be called: "Bang, you're dead". Your destructor must. Not. Throw. Resist.
edit: Relevant section from the Standard (14882 2003), 15.2 Constructors and Destructors [except.dtor]
:
15.2.3 The process of calling destructors for automatic objects constructed on the path from a try block to a throw-expression is called “stack unwinding.” [Note: If a destructor called during stack unwinding exits with an exception, terminate is called (15.5.1). So destructors should generally catch exceptions and not let them propagate out of the destructor. —end note]
Testcase for playing around (in real life, throw something that is derived from std::exception
, never throw int or something else!):
#include
int main() {
struct Foo {
~Foo() {
throw 0; // ... fore, std::terminate is called.
}
};
try {
Foo f;
throw 0; // First one, will be the active exception once Foo::~Foo()
// is executed, there- ...
} catch (int) {
std::cout << "caught something" << std::endl;
}
}