Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

RAII is fine. If it's a language feature, APIs can provide that to you so you don't have to write RAII wrappers all the time.

Otherwise a generic _bracket_ operator could be introduced, similar to Python's `with` statement. In C it might be a bit hard to parameterize, but even if it just requires you to use a void, it's still an improvement vs. not having anything at all. (Talking about language features so `__attribute__((__cleanup__))` doesn't count.)

Imagine something like this:

    FILE* handle = bracket(fopen("data.bin", "rb"), fclose) {
        fread(..., handle);
        return;
        fwrite(..., handle);
    } // <-- implicitly calling fclose(handle), always
Edit: After writing this sample I could even an optional `else` block in case `fopen` returned `NULL`.

Edit2: Of course, syntax fine-tuning would be welcome. For instance, `handle` should be restricted to the bracket's scope.



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: