Skip to content

Comment on C++11: Try/Catch/Finally Pattern Using RAII & Lambdas

Comments

What the OP describes here is a common C++ pattern known as "scope guard" (check "Solution 4" in http://drdobbs.com/184403758). It was possible to implement it in C++03 with some tricks but C++11 lambdas make it much easier.

This is a very nice small implementation but, as always with C++, devil is in the details:

* Creation of an std::function needs a dynamic allocation, so if the allocation fails an exception will be thrown and if the finally is guarding a resource, the resource will be leaked

* std::function has a non-negligible calling overhead, hence this should not be used in performance-sensitive code

* Checking a condition inside the finally clause is not very elegant, a better idiom in C++ is to support dismissing a scope guard.

* The finallyClause may throw an exception, and since it is called in a destructor this is generally considered a bad idea. I don't know what could happen in this case, but some scope guard implementations I've seen catch the exception and explicitly call std::terminate(). I guess this is for performance reasons, because the destructor can be declared nothrow.

Here there is a more complex implementation, which addresses most of the corner cases:

http://channel9.msdn.com/Shows/Going+Deep/C9-Lectures-Stepha...

I get your points. In general, the use cases for this pattern are not production code. The post points out this is not a good way of handling resource and that the example is about debugging. It would be up to the implementer to ensure the finally clause does not throw and exception or to catch it (I think there is something about nesting).

As for memory allocation failures, my experience is that depends a lot on the platform. It is a common misconception that dynamic memory is likely to run out and therefore we need to worry about that but not automatic memory. However, I have seen stack overflow many many many more times than a genuine 'out of memory'. Further, if an application has actually run out of memory so badly that a allocation of the closure's internal storage barfs then I suspect it cannot be retrieved. Naturally this does not apply if your platform has a very low heap size (e.g. realtime hardware or some such).

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.