Original Post
I've seen a few proposed systems to apply design-by-contract to C++. They're a bit verbose. It's obvious that common assertions at the beginning of a function are enough to express pre-conditions. Post-conditions, however, are much trickier. You can slap some assert()'s at the end of your function body, but you can't guarantee that a previous piece of code won't return earlier. Especially when re-visiting old code, you can just add a new return and not care/not remember that some post-conditions must always be verified. It's tedious work, and hard to maintain all those assertions. So there's a tight relationship between clean-up when exiting scope and asserting post-conditions. It would be cool if we could instruct the compiler to run some code on scope exit, no matter what happens. This would be solved with the proposed keyword "finally", which is available in VS but has to be used with a "try" block, making it very intrusive (ie, try {...} finally {...} ). It's also not available on other compilers (AFAIK). With this in mind, I set out to re-create the "finally" keyword myself. Using it in design-by-contract:
void f() {
// pre-conditions:
assert(...);
// post-conditions:
finally {
assert(...);
assert(...);
}
// main body
}
It's also useful for other kinds of clean-up, undoing actions on error, logging, etc. I managed to do it with a macro to create a local class that executes a block of code in its destructor. The main advantage of the macro is that you can access the scope of the original function, which a simple local class usually can't do. Without that feature the method would be rendered obsolete. It's a macro, and I know many people don't like those. But anyways, before posting the code I'd like to gauge interest in this. Would you find it useful? Is there a simpler alternative? Jotaf