It just happened to me I wondered how resources are freed in the following case.
class Base {
Resource *r;
public:
Base() { /* ... */ }
~Base() {
delete r;
}
};
class Derived : public Base {
public:
Derived() { /* ... */ }
~Derived() {
/* Suddenly something here throws! */
}
};
int main() {
try {
Derived d;
} catch(...) {
/* what happened with Base::r !? */
}
}
Will the base class destructor be called if the derived class destructor throws? Or will there be a leak?
According to §15.2/2:
So the base class destructor should be called. That is, just like we know this will clean up the base class:
And that this will clean up the member:
This will also clean up the base class:
That's my understanding of the quote.
The base destructor will get called.
In Effective C++, Meyers recommends that exceptions shouldn't leave destructors. Catch the exception inside the destructor and handle it, swallow it or terminate.
The base class destructor is indeed called. Sample code:
This prints: