Re:Allocgate: Restructuring how allocators work in Zig
by jcelerier on Wednesday December 15, 2021 @04:31PM
(#29571890)
> 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")};
}
Re:Allocgate: Restructuring how allocators work in Zig
by spacechild1 on Wednesday December 15, 2021 @07:22PM
(#29573303)
That's what I do as well. Many people are not aware that std::unique_ptr can do more than just manage heap memory.
Re:Allocgate: Restructuring how allocators work in Zig
by 10000truths on Wednesday December 15, 2021 @04:54PM
(#29572085)
Now 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.
Re:Allocgate: Restructuring how allocators work in Zig
by jcelerier on Wednesday December 15, 2021 @06:02PM
(#29572678)
This 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://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.