skip to content

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%

answer

  1. where the deleter is stored
  2. template argument vs constructor argument
  3. empty types take no space
  4. the control block erases the type

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.

solid answer

~40 s

`std::unique_ptr<T, D>` stores a `D` next to the pointer. Different deleters make different types, which cannot be assigned to each other, and the deleter's size is added to the object: an empty function object or captureless lambda costs nothing on libc++ and libstdc++ (both use an empty-member layout), so `sizeof` stays one pointer, while a function-pointer deleter doubles it and must be passed to every constructor. `std::shared_ptr<T>` receives the deleter as a constructor argument and stores it, type-erased, in the separately allocated control block. So every `shared_ptr<FILE>` has the same type and size whatever deleter it was built with, and `std::get_deleter<D>(sp)` recovers it. Prefer a named function object to `decltype(&std::fclose)`: it is smaller, and the standard leaves forming a pointer to most standard library functions unspecified.

code

cpp · 26 lines
cpp
#include <cstdio>
#include <iostream>
#include <memory>

void close_file(std::FILE* f) { std::fclose(f); }
struct FileCloser {
    void operator()(std::FILE* f) const noexcept { std::fclose(f); }
};

int main() {
    auto close_lambda = [](std::FILE* f) { std::fclose(f); };
    using ByFnPtr  = std::unique_ptr<std::FILE, void (*)(std::FILE*)>;
    using ByObject = std::unique_ptr<std::FILE, FileCloser>;
    using ByLambda = std::unique_ptr<std::FILE, decltype(close_lambda)>;
    std::cout << "FILE*                " << sizeof(std::FILE*) << '\n'
              << "fn-pointer deleter   " << sizeof(ByFnPtr) << '\n'
              << "FileCloser deleter   " << sizeof(ByObject) << '\n'
              << "lambda deleter       " << sizeof(ByLambda) << '\n'
              << "shared_ptr<FILE>     " << sizeof(std::shared_ptr<std::FILE>) << '\n';

    ByFnPtr a(std::fopen("a.txt", "w"), &close_file);   // must pass the pointer
    std::shared_ptr<std::FILE> c(std::fopen("c.txt", "w"), FileCloser{});
    std::shared_ptr<std::FILE> d(std::fopen("d.txt", "w"), close_lambda);
    c = d;   // one type, whatever deleter each was built with
    std::cout << "c now holds a FileCloser: " << (std::get_deleter<FileCloser>(c) != nullptr) << '\n';
}

go deeper

for a junior

Recall that unique_ptr names its deleter in its type, while shared_ptr takes the deleter as a constructor argument.

for a middle

Explain where each pointer stores the deleter and why that makes unique_ptr types incompatible across deleters but leaves shared_ptr types alone.

for a senior

Quantify the cost: an empty deleter is free on libc++ and libstdc++, a function pointer doubles the object and blocks default construction, and the addressable-function rule argues for function objects.

for a principal

Standardise one aliased owner type per C handle with an empty deleter, so APIs exchange one type and nobody pays for a function-pointer deleter.

## Two designs for the same job Both standard smart pointers can call a custom deleter, but they bind it at different times. - `std::unique_ptr<T, D>` takes the deleter **type** `D` as a template argument and stores a `D` object **inside** the `unique_ptr`. The deleter is known at compile time and can be inlined. - `std::shared_ptr<T>` has no deleter template parameter. Its constructor `template<class Y, class D> shared_ptr(Y* p, D d)` accepts any deleter and stores it in the **control block**, the separately allocated record that also holds the reference counts. Everything else in this answer follows from those two choices. ## unique_ptr: the deleter is part of the type Because `D` is a template argument, `std::unique_ptr<std::FILE, FileCloser>` and `std::unique_ptr<std::FILE, void (*)(std::FILE*)>` are **different types**. A function that takes one cannot take the other, and one cannot be assigned to the other. A codebase usually settles this with one alias per handle type, such as `using File = std::unique_ptr<std::FILE, FileCloser>;`. The deleter's size is added to the object: | Deleter type | `sizeof` on libc++, 64-bit | Default-constructible | |---|---|---| | none (`default_delete`) | 8 | yes | | empty function object `FileCloser` | 8 | yes | | captureless lambda type (C++20 `decltype`) | 8 | yes | | function pointer `void (*)(std::FILE*)` | 16 | no, must be passed in | | lambda capturing state | grows with its captures | no | The zero-cost rows are **an implementation choice, not a guarantee**: libc++ stores pointer and deleter in a compressed pair, and libstdc++ stores them in a `std::tuple`, whose layout also lets an empty member take no space. A function pointer cannot be compressed, so it doubles the object, adds an indirect call that the optimiser may not see through, and, because a null function pointer would be useless, the single-argument and default constructors are disabled for a pointer deleter: `std::unique_ptr<std::FILE, decltype(&std::fclose)> f(std::fopen(p, "r"));` does not compile. ## The decltype(&std::fclose) idiom The idiom is common, and it has a second problem. Since C++20, the standard library rules say that forming a pointer to a standard library function that is not designated an **addressable function** is unspecified (possibly ill-formed); `std::fclose` is not designated addressable. Most toolchains accept it today, but a named function object avoids the question, is smaller, and is easier to inline. In C++20 a lambda type works too: `std::unique_ptr<std::FILE, decltype([](std::FILE* f) { std::fclose(f); })>`. ## shared_ptr: the deleter is type-erased `std::shared_ptr` already allocates a control block for its counts, so it stores the deleter there and remembers only how to call it. Consequences: - every `std::shared_ptr<std::FILE>` has **one type**, whatever deleter it was built with, so they can be assigned, stored in one container and passed to one function; - `sizeof(std::shared_ptr<T>)` does not depend on the deleter (two pointers on libc++: the object pointer and the control-block pointer); - the deleter's size goes into the control block's allocation instead; - `std::get_deleter<D>(sp)` returns a `D*` to the stored deleter, or a null pointer if the deleter is not a `D`; - `std::make_shared` cannot take a deleter; a custom deleter always means the constructor form. ## Choosing a deleter in practice 1. **Default to an empty function object** with a `noexcept` call operator, one per release function, and alias the owner type (`using Image = std::unique_ptr<img_image, ImgCloser>;`). 2. **Use a C++20 lambda type** only where a named struct would be noise, for example a one-off in a test; it is equally free but harder to name in an error message. 3. **Reach for a function pointer** only when the release function is chosen at run time, such as a plugin that supplies its own close routine; accept the larger object and the extra argument at every construction. 4. **Use a stateful deleter** when the release needs context, for example a pool or a library context handle; the context is stored in every `unique_ptr`, which is usually still cheaper than a `shared_ptr`. 5. **Hand out `std::shared_ptr`** only when ownership is genuinely shared; the deleter then disappears from the type, which suits interfaces that must accept handles from several sources. ## Moving between the two A `std::unique_ptr<T, D>` converts to `std::shared_ptr<T>` by move, and the deleter travels with it into the new control block. The reverse is impossible: shared ownership cannot be handed back to a single owner. Wrapping a C library handle in a `unique_ptr` first and promoting it only when sharing is needed keeps the cheaper type as the default.

  • Why can't std::unique_ptr<std::FILE, void (*)(std::FILE*)> be constructed from the FILE* alone?
    Its constructors taking only a pointer, and the default constructor, are disabled when the deleter type is a pointer, because a value-initialized function pointer is null and calling it would be undefined behaviour. You must pass the function too: `p(std::fopen(path, "r"), &close_file)`. An empty function-object deleter has no such rule, because default-constructing it yields a usable deleter.
  • Does a custom deleter make a std::shared_ptr more expensive to create?
    It cannot use `std::make_shared`, so the control block is always its own allocation, separate from the object, and it grows by the deleter's size. Copies and the pointer itself cost the same as for any `shared_ptr`. Creating the handle as a `unique_ptr` with the deleter and moving it into a `shared_ptr` only when sharing is needed avoids the cost for the common case.

  • Every std::unique_ptr is exactly the size of a raw pointer
  • A custom deleter makes std::shared_ptr<FILE> a different type
  • decltype(&std::fclose) is the deleter the standard recommends
  • std::make_shared accepts a custom deleter as its last argument
  • The standard guarantees an empty deleter adds no space

Assumes C++23; a lambda type spelled with decltype as a deleter needs C++20, and the rule against forming pointers to standard library functions dates from C++20.