skip to content

Custom Deleters

A custom deleter lets a smart pointer close a FILE*, a socket or a C library handle. Interviewers ask how the deleter type changes unique_ptr's size and type but not shared_ptr's.

on this pageshow

explore

questions

4

Why does a C++ std::unique_ptr holding a FILE* from fopen need a custom deleter instead of the default one?

level: juniorimportance: should knowfreq 55%

answer

  1. who allocated it decides who frees it
  2. what default_delete calls
  3. fopen pairs with fclose
  4. a deleter as the second template argument

basics

~20 s

The 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
cpp
#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 behaviour

go deeper

for a junior

Recall that unique_ptr's default deleter calls delete, so anything not created with new needs its own deleter, such as one calling fclose.

for a middle

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.

for a senior

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.

for a principal

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
open as a page

Why does a custom deleter change a C++ std::unique_ptr's type and possibly its size, but not a std::shared_ptr's?

level: seniorimportance: should knowfreq 45%

basics

~20 s

For std::unique_ptr the deleter is a template argument stored inside the object, so it changes the type and, unless it is an empty type, the size. std::shared_ptr takes the deleter as a constructor argument and hides it in its control block.

open as a page

In C++23, how do std::out_ptr and std::inout_ptr let a std::unique_ptr receive a handle from a C function's pointer-to-pointer parameter?

level: middleimportance: nice to knowfreq 25%

basics

~10 s

std::out_ptr(p) makes a temporary that stands in for the C function's out-parameter and, at the end of the full-expression, resets p with the handle written into it; std::inout_ptr also passes p's current handle in

open as a page

Why can a C++ std::shared_ptr<std::FILE> with an fclose deleter misbehave after fopen fails, when std::unique_ptr does not?

level: seniorimportance: nice to knowfreq 30%

basics

~20 s

std::unique_ptr calls its deleter only for a non-null pointer, but a std::shared_ptr built from a null pointer and a deleter owns that null pointer and calls the deleter with it, so fclose(nullptr) runs, which is undefined behaviour.

open as a page