3 ms·
Defer can be emulated with the block extensions of Clang and GCC [0], though I'm not sure how much I'd like to see something like that in a codebase. [0] https
by shakna 7y ago
Defer can be emulated with the block extensions of Clang and GCC [0], though I'm not sure how much I'd like to see something like that in a codebase.
[0] https://web.archive.org/web/20180426195701/http://fdiv.net/2015/10/08/emulating-defer-c-clang-or-gccblocks https://web.archive.org/web/20180426195701/http://fdiv.net/2...
- gnulinux 7y agoThat link seems to be broken? Nothing opens when I click it.
- saagarjha 7y agoWorks fine for me. It's using __attribute__((cleanup)) to call a function that calls the block you give it.
- shakna 7y agoIt's a short article, and worth reading if you can work out why the Wayback Machine isn't working for you. The magic is basically: static inline void defer_cleanup(void (^*b)(void)) { (*b)(); } #define defer_merge(a,b) a##b #define defer_varname(a) defer_merge(defer_scopevar_, a) #define defer __attribute__((cleanup(defer_cleanup))) void (^defer_varname(__COUNTER__))(void) = Which let's you do: FILE *a = fopen ("a.txt", "r"); if (!a) return EXIT_FAILURE; defer { fclose (a); }; It uses cleanup and blocks, both of which are extensions. There may also be some strangeness with the way blocks hold memory. (Block references become const copies).
- Twirrim 7y agohttp://fdiv.net/2015/10/08/emulating-defer-c-clang-or-gccblocks http://fdiv.net/2015/10/08/emulating-defer-c-clang-or-gccblo... The original link works.
- shakna 7y agoThe original link pops up with a HTTP basic authentication request for me, hence the use of archive.
- simias 7y agoThere's also __attribute__ ((__cleanup__(<destructor>))) which can be used to implement RAII in C.
- shakna 7y agoThat's exactly what this uses. It just hides it inside a syntax that is more similar to what Go uses.
- simias 7y agoAh, apologies, the link wasn't loading at the moment and I assumed it was something else. Regarding its use in the wild, I've encountered it exactly once, in the lastpass-cli (available on github). I personally wouldn't consider using it for one of my projects because it's too nonstandard, however I suppose that for a security-sensitive application it might reduce the likelihood of messing error handling and leaking things all over the place. That being said using non-standard features might also make it more likely for a contributor to misunderstand what the code does precisely and introduce a problem.
- cyphar 7y agoLXC uses it as well, and they have additional macros to "move" pointers and file descriptors to make sure you don't double-free or similar things.