If your project is written in C, and you don’t mind having a hard dependency on GCC (i.e. you don’t care about building with MSVC++), this GNU C extension does amazing things for your code.
There are other GNU C extensions that are simultaneously useless and crazy, but __attribute__ ((cleanup)) makes up for everything else. For reference, here’s a discussion about using it in GNOME.
pretty cool indeed.
I was also planning to propose a wrapper for __attribute__((nonnull, argidx, …)) to get compiler warnings when passing NULL, instead of getting run-time warnings only through g_return_if_fail()/g_return_val_if_fail().
I was somehow convinced I used something like G_GNUC_NONNULL before, but looks like I’m mixing things up 🙂
I defined something similar at https://github.com/Incubaid/crakoon/blob/master/src/arakoon.h#L112 and it has proved to be useful already.
Automatically running a cleanup function when a variable goes out of scope? That’s really neat. I seem to recall some Danish guy invented a C extension to do that a while ago, along with a few other useful things. He called it “C with Classes” or something. Does anyone know what happened to it?
Yeah, I know what you’re talking about… I believe it still has a modest cult following, and the latest version has type inferencing, garbage collection, even macros (after a fashion)… what’s it called? It was on the tip of my tongue… Chainsaw?
Indeed, this feature is one of the best parts of C++, but there’s a *whole lot* of other stuff that comes with C++, not all of it good…
Anyways, the model where the best ideas filter back down into C is nice.
+1 for Tristan. “cleanup” is a hack to provide destructors in C, and the implementation uses the same code as GCC uses for that Danish guy’s C extension. With a little more effort, you can modify this hack to work either with the GCC cleanup extension, or with any C++ compiler.
What I find ironic is that you linked to nested functions as “useless and crazy”… but the very example of cleanup that you linked to in wikipedia uses a nested function in the #define to create a local nested destructor!
Nevermind, thank you a lot for the information! Although I agree with Joe that cleanup is a hack, I am sure to use it more and more in my own code!
Very impressive. I wonder how much work it would take to generalize from this to Go’s “defer” mechanism?