Sunday 15 February 2004 — This is close to 21 years old. Be careful.
One of the most powerful features of C++ is that stack objects are guaranteed to be destroyed as functions are exited, regardless of why they were exited (normal return, or an exception being thrown). This is one of those clever techniques that is easy to know about, but then easy to overlook anyway (as I recently did). I’ve written an article about it: Destructors instead of catches.
Comments
Exceptions may be unavoidable in code that's called by a destructor -- the important thing is that the destructor does not allow them to propagate through it. You may need to resort to a catch (...) { } block if you're paranoid -- you should try to keep your destructors as simple as possible.
Why does this matter? Well, if you define a Resource allocator in one block in a function and then have another block further down that does the same thing, has the destructor for the first resource been released yet? If the answer is vendor-specific then your code would need to be broken up into separate functions/methods to work properly everywhere. Also, some people are crazy enough to have nested exception handling in functions/methods. Destructor behavior needs to work properly here too.
By the way, are the comments on the blog entry separate from the comments on the article? Should I be putting my comments there instead?
Add a comment: