(no title)
kjgkjhfkjf | 9 days ago
Both RAII and `defer` have proven to be highly useful in real-world code. This seems like a good addition to the C language that I hope makes it into the standard.
kjgkjhfkjf | 9 days ago
Both RAII and `defer` have proven to be highly useful in real-world code. This seems like a good addition to the C language that I hope makes it into the standard.
Zambyte|9 days ago
rwmj|9 days ago
By the way, GCC and Clang have attribute((cleanup)) (which is the same, scope-based clean-up) and have done for over a decade, and this is widely used in open source projects now.
CodesInChaos|9 days ago
bashkiddie|9 days ago
In Golang if you iterate over a thousand files and
your OS will run out of file descriptorsjibal|9 days ago
L-4|9 days ago
I think that defer is actually limited in ways that are good - I don't see it introducing surprising control flow in the same way.
kibwen|9 days ago
> RAII has also proven to be quite harmful in cases
The downsides of defer are much worse than the "downsides" of RAII. Defer is manual and error-prone, something that you have to remember to do every single time.
fauigerzigerk|9 days ago
It allows library authors to take responsibility for cleaning up resources in exactly one place rather than forcing library users to insert a defer call in every single place the library is used.
throwaway27448|9 days ago
mort96|9 days ago
But yeah, RAII can only provide deterministic destruction because resource acquisition is initialization. As long as resource acquisition is decoupled from initialization, you need to manually track whether a variable has been initialized or not, and make sure to only call a destruction function (be that by putting free() before a return or through 'defer my_type_destroy(my_var)') in the paths where you know that your variable is initialized.
So "A limited form of RAII" is probably the wrong way to think about it.
ceteia|9 days ago
[deleted]
usrnm|9 days ago
randusername|9 days ago
I got out my 4e Stroustrup book and checked the index, RAII only comes up when discussing resource management.
Interestingly, the verbatim introduction to RAII given is:
> ... RAII allows us to eliminate "naked new operations," that is, to avoid allocations in general code and keep them buried inside the implementation of well-behaved abstractions. Similarly "naked delete" operations should be avoided. Avoiding naked new and naked delete makes code far less error-prone and far easier to keep free of resource leaks
From the embedded standpoint, and after working with Zig a bit, I'm not convinced about that last line. Hiding heap allocations seems like it make it harder to avoid resource leaks!
omoikane|9 days ago
The extra braces appear to be optional according to the examples in https://www.open-std.org/JTC1/SC22/WG14/www/docs/n3734.pdf (see pages 13-14)