News for hackers. Stuff that matters.
Re:A Defer Mechanism for C by coldtea on Monday December 14, 2020 @09:03AM (#25417600)
The whole point is that it's much easier to NOT forget defer (which goes right after the resource acquisition line), than to forget to free the resource (which happens much further down the function).

So it's immediately better compared to the current C situation.

As for compared to RAII? Well, thats one failure mode for defer (forgetting it), whereas there are dozens of ways to mess RAII...

Re:A Defer Mechanism for C by CyberRabbi on Monday December 14, 2020 @09:12AM (#25417707)
I made no comparison between “defer” and the current C situation.

In comparison to RAII, “defer” as a language feature is a kludge. Mainly because RAII completely solves the problem of correct resource cleanup for API users while “defer” does not.

Re:A Defer Mechanism for C by fnord123 on Monday December 14, 2020 @03:38PM (#25422946)
RAII is a delight when it comes to local heap memory. However, if you want to pair fclose with a fopen call then you need to wrap fopen in a type and make the destructor call fclose. This is totally fine and I like it a lot in C++ and Rust, but it doesn't gel with existing C apis. Therefore I think defer is a good choice for C regardless of what I might choose were I to be implementing a language from scratch.
Re:A Defer Mechanism for C by coldtea on Monday December 14, 2020 @09:28AM (#25417905)
RAII is an idiom, not a language feature. Destructors might be the language feature, but they have their own issues and caveats.

So I don't see the comparison...

Re:A Defer Mechanism for C by isogon on Monday December 14, 2020 @10:03AM (#25418320)
I think it's quite reasonable to compare defer and destructors, in that case.

Destructors probably cannot be usefully imported into C while preserving the simplicity of the language: then you'll want at least unique_ptr to manage your memory with destructors, then probably shared_ptr, and some ownership semantics as you pass those around, et cetera. In that sense, defer strikes a balance between simplicity and usefulness. However, there is still a comparison.