3 ms·
I really want to like Zig. Honest question: why is Zig so resistant to some kind of RAII? RAII is the biggest improvement that C++ brings over C. Leaving it out
by igor_akhmetov 3y ago
I really want to like Zig. Honest question: why is Zig so resistant to some kind of RAII? RAII is the biggest improvement that C++ brings over C. Leaving it out of a system programming language 50 years later is just strange? And no, manual defer is not the solution.
- throwaway17_17 3y agoThe most frequently given reason is that a core principle for Zig is ‘No implicit control flow’ or just the more general ‘Explicit is always better’. RAII, both for constructors and destructors are inherently implicit control flow constructs, also they usually involve access to allocation primitives, which Zig also rejects when implicit. You can disagree with the language principles if that is one’s position. However, the ‘resistance’ to RAII is a clear effect of those principles.
- gpderetta 3y agoI assume that zig requires the programmer to also manually allocate and free stack frames? And it eschews functions as they can hide allocations and control flows?
- schemescape 3y agoI would assume "allocation primitives" is referring to the heap.
- mk12 3y agoI felt that way at first too but I’m less concerned about it the more I use Zig. Defer and errdefer are already a huge improvement over C. I won’t deny there’s more risk of forgetting to clean up than in Rust or C++, but Zig’s approach forces me to think more clearly about what’s going on. For example, instead of doing a slow tree traversal to free little bits of memory all over the place (which RAII would do implicitly), in Zig I’d probably use an arena and free it all at once. A similar principle applies to other non-memory resources too (though maybe not mutexes for example). I also think it would be difficult to achieve the flexibility of Zig’s unmanaged containers (where deinit takes a parameter) in a RAII language.
- kristoff_it 3y ago> I really want to like Zig. Don't try to like Zig and instead make sure your cup is empty before entering a new tea shop.