RAII in C
RAII in C
Posted Mar 5, 2014 21:29 UTC (Wed) by cesarb (subscriber, #6266)In reply to: RAII in C by bronson
Parent article: A longstanding GnuTLS certificate validation botch
systemd's way is:
void foo(void) {
_cleanup_fclose_ FILE *f = NULL;
...
}
Using the following definitions:
#define _cleanup_(x) __attribute__((cleanup(x)))
static inline void fclosep(FILE **p) {
if (*p)
fclose(*p);
}
#define _cleanup_fclose_ _cleanup_(fclosep)
(Actually, fclosep is defined via another macro, DEFINE_TRIVIAL_CLEANUP_FUNC, but it expands to the static inline I typed above.)
Not that ugly (compare "_cleanup_fclose_ FILE *f = NULL;" with a C++ equivalent of "scoped_FILE f(nullptr);", assuming an equivalent scoped_FILE helper class). Yes, C++'s way is slightly cleaner to use (and way more complex to define), but the difference is not that big.
Posted Mar 6, 2014 18:43 UTC (Thu)
by bronson (subscriber, #4806)
[Link] (1 responses)
Looking forward to playing with these macros next time I'm waist deep in C.
Posted Mar 6, 2014 22:52 UTC (Thu)
by cesarb (subscriber, #6266)
[Link]
RAII in C
RAII in C
