4 ms·
`defer` and `errdefer` give you 90% of what destructors & co give you for 0% of the complexity. For now the the closest thing to RAII is this proposal, but the
by kristoff_it 5y ago
`defer` and `errdefer` give you 90% of what destructors & co give you for 0% of the complexity.
For now the the closest thing to RAII is this proposal, but there is no guarantee that it will be accepted.
https://github.com/ziglang/zig/issues/782 https://github.com/ziglang/zig/issues/782
- initplus 5y agoI find in C++ at least reasoning about RAII is always surprisingly complex. The second you have to write a custom destructor you get into the weeds of reasoning about copy/move/copy-assignment etc. https://en.cppreference.com/w/cpp/language/rule_of_three https://en.cppreference.com/w/cpp/language/rule_of_three C++ RAII also rubs up painfully against handle based APIs (looking at you Windows) in my experience. There is a lack of standardized RAII wrappers for handle types like there is for pointers. Yes you can pull in a custom handle RAII wrapper but at that point it's simpler to just manage manually. Defer on the other hand is simple. Anyone can understand it in five minutes.
- jcelerier 5y ago> There is a lack of standardized RAII wrappers for handle types like there is for pointers. .. what's wrong with #include <memory> template<typename T, auto Free> using safe_handle_t = std::unique_ptr<T, decltype([] (auto p) { Free(p); })>; using file_handle = safe_handle_t<FILE, fclose>; void file_example() { file_handle f{fopen("foo", "r")}; }
- 10000truths 5y agoNow you have a double indirection. Worse, the handle probably already references dynamically allocated memory. So that’s two dynamic memory allocations per “safe” handle. Which might be perfectly acceptable for non-critical programs, but it is certainly going to tank your memory usage efficiency and thrash your CPU cache if scaled up to millions of handles.
- fbkr 5y agoThere is no double indirection and allocation here, it stores the FILE* directly, not as a pointer to a FILE*.
- jcelerier 5y agoThis is entirely wrong. This produces exactly the same code than auto f = fopen("foo", "r"); if(f) fclose(f); check for yourself: https://gcc.godbolt.org/z/YxaPqYGez https://gcc.godbolt.org/z/YxaPqYGez
- spacechild1 5y agoThat's what I do as well. Many people are not aware that std::unique_ptr can do more than just manage heap memory.
- dnautics 5y agoI'm pinning my hopes that certain types can be marked as "shared resources", either in-lang, or through a minimalistic helper tool - and analyzed at a lower level (ZIR or AIR) for lifetime analysis.