Hacker News new | ask | show | jobs
by bluetomcat 752 days ago
> Can you write _new_ C code that "does RAII" ? Probably.

You can do "manual" goto-based RAII in C, and it has been done for decades. The end of your function needs to have a cascading layer of labels, undoing what has been done before:

    if (!(x = create_x())) {
        goto cleanup;
    }

    if (!(y = create_y())) {
        goto cleanup_x;
    }

    if (!(z = create_z())) {
        goto cleanup_y;
    }

    do_something(x, y, z);

    cleanup_z:
    destroy_z(z);
    cleanup_y:
    destroy_y(y);
    cleanup_x:
    destroy_x(x);
    cleanup:
    return;
It just takes more discipline and is more error-prone maintenance-wise.
2 comments

That's not RAII, that's 'defer'. defer and context managers are both implementations of a subset of the kind of functionality you can get with RAII (the two missing parts are 1) allowing you to place an RAII object in part of a larger structure and have confidence it will actually be constructed and destructed correctly, and 2) allowing the representation of lifetimes which are more complex then just 'in this scope' via moves and copies).
except this misses the point of RAII.