4 ms·
> 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
by bluetomcat 2y 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.
- gpderetta 2y agoexcept this misses the point of RAII.
- rcxdude 2y agoThat'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).