User: Password:
|
|
Subscribe / Log in / New account

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.


(Log in to post comments)

RAII in C

Posted Mar 6, 2014 18:43 UTC (Thu) by bronson (subscriber, #4806) [Link]

Hm, not bad... My overengineering spidey sense is tingling a bit but, I agree, it doesn't seem any worse than other non-GC solutions.

Looking forward to playing with these macros next time I'm waist deep in C.

RAII in C

Posted Mar 6, 2014 22:52 UTC (Thu) by cesarb (subscriber, #6266) [Link]

It might look like overengineering because I only showed one of the _cleanup_*_ definitions. The version of the systemd code I'm looking at has nine different _cleanup_*_ variants, four of them defined via the DEFINE_TRIVIAL_CLEANUP_FUNC macro. Search for _cleanup_ at http://cgit.freedesktop.org/systemd/systemd/tree/src/shar... (and pretend the rest of that file does not exist; it lives up to the tradition of a module called "util" being used as a dumping ground for assorted bits and pieces).


Copyright © 2017, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds