
Manual resource management in low level C-style C++ code might be annoying. It's not practical to create good enough RAII wrappers for every single C API you use, but approaches with goto cleanup
or loads of nested if (success)
hurt readability.
A defer
macro to the rescue! The deferred lambda will be executed on scope exit, no matter how it happens: you can return
from any point, throw
an exception (if allowed), or even use a goto
to an outer scope. It is truly zero-cost and doesn't rely on C runtime or standard library, so it can be used even in kernel development.