golang's defer in C (kind of)

Contents
Quite often I find myself landing on gcc’s attributes documentation page. Not
sure how that happens but this is always a gold mine. I’ve recently discovered
__attribute__((cleanup(func))), which allows attaching functions to
variables. These functions are executed when the variable goes out of scope.
Sounds familiar?
Missing piece of a puzzle
__attribute__((cleanup(func))) is the building block that C is missing. It’s
perfect for simple resource management and an answer to implement things akin
to
Boost.ScopeExit
are equivalent of C++’s RAII. I’m gonna cut straight to the chase.
|
|
The next obvious step is to dress this up with some helpful macros:
|
|
Of course, this is not portable but it’s good to be aware such feature exist.
^varattr: GNU gcc variable attributes