Why does a C++ std::unique_ptr holding a FILE* from fopen need a custom deleter instead of the default one?
answer
- who allocated it decides who frees it
- what default_delete calls
- fopen pairs with fclose
- a deleter as the second template argument
basics
~20 sThe default deleter, std::default_delete, calls delete, but a FILE* from fopen was not created by new: deleting it is undefined behaviour and never runs fclose, so buffered output is lost. A deleter whose call operator runs fclose fixes it.
solid answer
~40 s`std::unique_ptr<T>` is really `std::unique_ptr<T, std::default_delete<T>>`, and `default_delete<T>` releases the pointer with `delete`. A `FILE*` comes from `std::fopen`, which the C library allocates however it likes, so `delete` on it is undefined behaviour, and `fclose` (which flushes the buffer and closes the descriptor) never runs. The fix is a second template argument: a deleter type whose `operator()` calls `std::fclose`, for example `struct FileCloser { void operator()(std::FILE* f) const noexcept { std::fclose(f); } };` and then `std::unique_ptr<std::FILE, FileCloser>`. The `unique_ptr` destructor calls the deleter only when the stored pointer is not null, so a failed `fopen` is safe. For an opaque C handle whose struct is only declared, the default deleter does not even compile, because `default_delete` requires a complete type.
code
cpp · 7 lines#include <cstdio>
#include <memory>
int main() {
std::unique_ptr<std::FILE> log(std::fopen("ingest.log", "w")); // BUG
std::fputs("frame 1\n", log.get());
} // ~unique_ptr calls delete on a pointer fopen produced: undefined behaviourgo deeper
Recall that unique_ptr's default deleter calls delete, so anything not created with new needs its own deleter, such as one calling fclose.
Explain the deleter as the second template parameter, why an empty function object is the idiomatic choice, and that a null pointer never reaches it.
Point out that delete on a FILE pointer compiles silently and loses buffered data, while an opaque handle fails to compile, which is the failure you want.
Push for one aliased owner type per C handle in a codebase, so nobody writes a raw close call or picks a deleter at each call site.
## What the default deleter does Every `std::unique_ptr` has two template parameters: the pointee type and a **deleter** type, `template<class T, class D = default_delete<T>> class unique_ptr;`. The deleter is a function object that the `unique_ptr` calls to release what it owns. The default, `std::default_delete<T>`, does exactly one thing: `delete ptr;` (or `delete[] ptr;` for the array form). That is correct only for memory obtained with the matching `new`. Anything else (a C library handle, a `FILE*`, memory from `malloc`, a pointer into a pool) needs a different release call, and `unique_ptr` learns which one from the deleter. ## Why delete on a FILE* is wrong twice over `std::fopen` returns a pointer to a `FILE` object that the C library created by its own means. Calling `delete` on it: - is **undefined behaviour**, because the pointer did not come from a `new` expression; on the machine used to check this answer, the program aborted, and AddressSanitizer reported "attempting free on address which was not malloc()-ed"; - **skips `fclose`**, so data still in the stream's buffer is never written and the file descriptor is never released; - compiles silently on platforms where `FILE` is a complete type, which is the dangerous part: nothing warns. For an **opaque handle** (a C imaging library that only declares `struct img_image;` in its header), `std::unique_ptr<img_image>` does not compile at all: `default_delete`'s call operator requires a complete type. That error is the useful one, and the fix is the same. ## Writing the deleter The deleter is any type that can be called with the stored pointer. The idiomatic choice is an empty function object: ```cpp struct FileCloser { void operator()(std::FILE* f) const noexcept { std::fclose(f); } }; using File = std::unique_ptr<std::FILE, FileCloser>; ``` Points worth saying aloud: 1. The deleter's type is the **second template argument**; an empty type like `FileCloser` is default-constructed, so `File f(std::fopen(...));` needs no extra argument. 2. Mark the call operator `noexcept`: the standard makes it undefined behaviour for the deleter to throw from `~unique_ptr`. 3. Check the result of `fopen` before using it. `if (!f)` works because `unique_ptr` converts to `bool`. 4. The `unique_ptr` destructor calls the deleter **only when the pointer is not null**, so a failed `fopen` needs no special case in `FileCloser`. ## Choices for the deleter type | Deleter | Example | Notes | |---|---|---| | Empty function object | `FileCloser` | default-constructible, adds no size on common implementations | | Lambda type (C++20) | `decltype([](std::FILE* f) { std::fclose(f); })` | needs C++20, which allows lambdas in unevaluated operands | | Function pointer | `void (*)(std::FILE*)` | must be passed to every constructor, adds a pointer to the object | The size and type consequences of each choice, and how `std::shared_ptr` differs, are a separate question; the point here is that the release call must match the acquisition call. ## Wrong fixes that come up Candidates under pressure reach for fixes that do not work: - **Calling `release()` at the end.** `release()` gives up ownership and returns the raw pointer; it closes nothing, so the stream leaks unless the caller closes it by hand. - **Calling `fclose(f.get())` and keeping the default deleter.** The stream is closed, and then `default_delete` still runs `delete` on the dangling pointer at scope exit. - **Using `std::make_unique`.** It always allocates with `new` and always uses the default deleter; it cannot adopt a pointer from `fopen` at all. - **Switching to `std::unique_ptr<std::FILE[]>`.** The array form changes `delete` to `delete[]`, which is just as wrong. Each of these keeps the wrong release call somewhere. Only a deleter that calls the matching C function fixes the pairing. ## The same pattern for any C handle Every acquire/release pair in a C API maps onto the same shape: `img_open`/`img_close`, `fopen`/`fclose`, `malloc`/`free`. Write one empty deleter per release function, alias the resulting `unique_ptr`, and the handle closes itself on every exit, including exceptions.
- Why does std::unique_ptr<img_image> fail to compile when the C header only declares struct img_image?`std::default_delete<T>::operator()` requires `T` to be a complete type, because `delete` on an incomplete type cannot run its destructor. With an opaque C struct the type is never completed, so the default deleter is rejected at compile time; a deleter calling the library's close function needs only the pointer and compiles fine.
- Should the custom deleter itself check for a null FILE* before calling fclose?For `std::unique_ptr` it is not needed: its destructor and `reset` call the deleter only with a non-null pointer. A null check costs nothing, though, and makes the same deleter safe to reuse with `std::shared_ptr`, which does call its deleter for a null pointer it was constructed with.
- std::unique_ptr<FILE> calls fclose automatically for a FILE pointer
- default_delete frees with std::free when the pointer came from C
- Calling release() at scope exit closes the stream properly
- std::make_unique can be given fclose as the deleter
- The deleter must check for null because unique_ptr calls it anyway