3 ms·
> There is a lack of standardized RAII wrappers for handle types like there is for pointers. .. what's wrong with #include <memory> template<typename
by 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.