Module 8 · Lesson 14 of 90

Custom deleters and factory functions

Wrap FILE*, malloc buffers, and POSIX fds in smart pointers with custom deleters, prefer make functions, and return unique_ptr from factories to eliminate raw new/delete.

  • Beginner to advanced
  • 8 min read
  • 25 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM with g++ (GCC 13); no board needed

Your place in the module
By the end you can 4 objectives
  • Wrap a C resource (FILE*, malloc buffer, POSIX fd) in a smart pointer with the correct custom deleter
  • Explain why make_unique and make_shared are preferred over new, including the exception-safety argument
  • Return std::unique_ptr from a factory function and transfer ownership with std::move
  • State what C++ Core Guidelines R.3 and R.11 require and how this lesson's tools satisfy them
Video coming soonCustom deleters and factory functions
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from unique_ptr and exclusive ownership
  • std::unique_ptr is move-only: its copy operations are deleted, and a move leaves the source empty (nullptr)
  • get() returns a non-owning observer pointer, release() gives up ownership without deleting, and reset() deletes the current object
  • With the default deleter, libstdc++ makes unique_ptr the same size as a raw pointer: 8 bytes on x86-64
01

Custom deleters: one owner, any cleanup function

4 min read

The previous lesson gave every heap object one owner through unique_ptr. This lesson shows how custom deleters, make_unique/make_shared, and factory returns let you delete raw new and delete from real code, including a POSIX fd wrapper.

The default unique_ptr<T> ends its object's life with delete. That is correct for objects created with new, but most resources on a Linux system are not created with new. A stdio stream comes from fopen and must end with fclose. A raw buffer comes from malloc and must end with free. A file descriptor comes from open and must end with close. Pairing the wrong release function with a resource is a bug: calling delete on a FILE* returned by fopen is undefined behaviour, and forgetting close leaks a kernel resource until the process exits. On a long-running embedded service, a slow fd leak eventually hits the per-process limit and every subsequent open fails with EMFILE.

A fixes the pairing once, at the type level. unique_ptr takes the cleanup policy as its second template parameter: std::unique_ptr<T, D>. When the owner dies, it calls d(get()). Wrapping a FILE* is one line:

cpp
#include <cstdio>
#include <memory>

std::unique_ptr<FILE, int (*)(FILE*)> log{std::fopen("app.log", "w"), &fclose};
if (!log) { std::perror("fopen"); return 1; }
std::fputs("started\n", log.get());   // get() observes, never releases
// scope exit calls fclose(log.get()), even if fputs or later code throws

Notice that the deleter is part of the type: unique_ptr<FILE, int (*)(FILE*)> (written with the explicit function-pointer type because decltype(&fclose) makes GCC 13 print a -Wignored-attributes warning under -Wall) and unique_ptr<FILE, SomeLambda> are different, incompatible types. That has a size consequence on 64-bit Linux. A function-pointer deleter is stored next to the resource pointer, so the owner is 16 bytes. A stateless lambda or an empty struct is folded into the owner by the empty-base optimisation, so the owner stays 8 bytes, exactly the size of a raw pointer. A deleter that captures state (a counter, a logger reference) stores that state inside the owner and grows it. Prefer a stateless lambda or a small struct:

cpp
auto file_closer = [](FILE* f) { if (f) std::fclose(f); };
std::unique_ptr<FILE, decltype(file_closer)> log{std::fopen("app.log", "w"), file_closer};

For malloc, use the array form so you get operator[] on the buffer:

cpp
std::unique_ptr<char[], decltype(&std::free)> buf{
    static_cast<char*>(std::malloc(4096)), &std::free};
if (!buf) { return 1; }
buf[0] = 'x';   // free(buf.get()) runs at scope exit

A file descriptor is harder because it is an int, not a pointer. The common unique_ptr trick stores the fd value in the pointer slot through std::intptr_t, and the deleter converts it back and calls close. The stored "pointer" is never dereferenced; it is only a container for the integer:

cpp
#include <cstdint>
#include <cstdio>
#include <memory>
#include <fcntl.h>
#include <unistd.h>

struct CloseFd {
    void operator()(int* p) const {
        if (p) ::close(static_cast<int>(reinterpret_cast<std::intptr_t>(p)));
    }
};
using FdPtr = std::unique_ptr<int, CloseFd>;

FdPtr wrap_fd(int fd) {
    return FdPtr{reinterpret_cast<int*>(static_cast<std::intptr_t>(fd))};
}
int raw_fd(const FdPtr& p) {
    return static_cast<int>(reinterpret_cast<std::intptr_t>(p.get()));
}

int main() {
    int raw = ::open("/etc/os-release", O_RDONLY | O_CLOEXEC);
    if (raw < 0) { std::perror("open"); return 1; }
    FdPtr file = wrap_fd(raw);
    char buf[128];
    ssize_t n = ::read(raw_fd(file), buf, sizeof buf);
    if (n < 0) { std::perror("read"); return 1; }
    std::printf("read %zd bytes\n", n);
    return 0;   // CloseFd runs here: close(raw)
}
bash
g++ -Wall -Wextra -std=c++20 fd.cpp -o fd
./fd

The program prints how many bytes it read; the count depends on the file. O_CLOEXEC asks the kernel to close the fd automatically on exec, which is good hygiene for descriptors anyway.

The fd trick has two sharp edges

Check open's return before wrapping: casting -1 into the pointer slot produces a non-null fake pointer that the deleter would try to close. And fd 0 (stdin) maps to the null pointer, so the wrapper treats it as empty and never closes it. For code that must handle fd 0 or wants a clean -1 sentinel, a dedicated RAII class is the right tool; the lesson "A RAII file descriptor wrapper" builds one. The unique_ptr trick is for the common case where you own a freshly opened fd numbered 1 or higher.

Deleter storage: unique_ptr vs shared_ptrunique_ptr<T,D>shared_ptr<T>Deleter in typeyesno (erased)Statelessdeleter size8 bytes16 bytesFunction pointerdeleter16 bytes16 bytesDeleter storedinside theownerin controlblock
Where each smart pointer keeps its deleter, and what that costs in size on 64-bit Linux
02

make_unique, make_shared, and the exception-safety argument

3 min read

Everything above still constructed owners from raw acquisition calls. For plain heap objects there is a better spelling. std::make_shared<T>(args...) arrived with C++11 and std::make_unique<T>(args...) with C++14; both forward their arguments to T's constructor and return a ready owner:

cpp
auto cfg  = std::make_unique<Config>(Config{100});   // no new anywhere
auto data = std::make_shared<std::vector<int>>(1024, 0);

The historical argument for make_* is exception safety. Consider this pre-C++17 call:

cpp
sink(std::unique_ptr<Config>(new Config), parse_flags());   // pre-C++17: leak risk

Before C++17, the compiler could interleave the two arguments: run new Config, then call parse_flags(), and only then construct the unique_ptr. If parse_flags() threw in between, the raw pointer was lost and the Config leaked. C++17 changed the evaluation rules: the arguments are still evaluated in an unspecified order, but the evaluation of one argument can no longer be interleaved with another, so this exact leak cannot happen in a C++17 build. The recommendation survived the fix anyway, for three reasons. First, make_* is safe under every standard, which matters when code moves between codebases compiled as C++14 and C++20. Second, it names the type once and contains no raw new to review, copy, or mismatch with a delete. Third, make_shared is genuinely more efficient: it allocates the object and the reference-count control block in a single allocation, while shared_ptr<T>(new T) performs two. The trade-off is that the single block cannot be freed while any weak_ptr still observes it; the later lessons on shared and weak ownership cover that cost.

There is one thing make_* cannot do: accept a custom deleter. make_unique and make_shared always use delete, so resources with a different release function go through the constructor directly. This is where shared_ptr shows a design difference worth knowing now:

cpp
std::shared_ptr<FILE> log{std::fopen("app.log", "w"), &fclose};

The type is just shared_ptr<FILE>. The deleter is not a template parameter; it is into the control block. Two shared_ptr<FILE> objects, one with &fclose and one with a capturing lambda, have the same type and can be assigned to each other; each still runs its own deleter. And sizeof(shared_ptr<T>) stays 16 bytes (two pointers: the object and the control block) no matter how large the deleter is, because the state lives in the control block, not in the pointer.

shared_ptr from new vs make_sharedshared_ptr<T>(new T)make_shared<T>()AllocationstwooneRaw new visibleyesnoException safetypre-C++17leak risksafe, everystandardCustom deletersupportednot supported
Constructing a shared_ptr with raw new versus make_shared: allocations, safety, and deleter support
Where new legitimately survives

After this lesson, the only new left in well-designed application code is inside an owner constructor for a case that make_* cannot express, such as a class with a private constructor, which make_unique cannot call, so it is built as std::unique_ptr<Widget>(new Widget) inside a static member function. Even that usually disappears behind a factory function, which is the next section's job.

03

Factory functions: returning ownership, deleting new/delete for good

3 min read

A is where the pieces of this lesson combine. The acquisition (whether new, fopen, or open) happens in exactly one place, checked for failure, and every caller receives a ready owner:

cpp
struct Config { int rate; };

std::unique_ptr<Config> load_config(int rate) {
    if (rate <= 0) return nullptr;               // failure: an empty owner
    return std::make_unique<Config>(Config{rate});
}

Returning unique_ptr by value compiles even though it is non-copyable: the return statement either elides the copy entirely (the object is constructed directly in the caller's storage) or implicitly moves. The caller receives exclusive ownership with no ceremony:

cpp
auto cfg = load_config(100);
if (!cfg) { /* handle failure */ }
use(*cfg);              // observe through a reference, not through the pointer
store(std::move(cfg));  // transfer: store takes unique_ptr<Config> by value

Three passing conventions follow from this. To let a function observe the object, pass Config& or Config*: the function has no business knowing how the object is owned. To transfer ownership into a function (a "sink"), take unique_ptr<Config> by value and require the caller to write std::move, which makes the handover visible at the call site. And when sharing really is needed, a unique_ptr converts to shared_ptr implicitly from an rvalue: std::shared_ptr<Config> shared = load_config(100); works, and the conversion even preserves a custom deleter. Starting exclusive and upgrading to shared is cheap; the reverse is not possible, so factories return unique_ptr by default.

This is the design the C++ Core Guidelines ask for. R.3 says "A raw pointer (T*) is non-owning": every T* you see should be an observer, and ownership lives in a named owner type. R.11 says "Avoid calling new and delete explicitly": allocation and release belong inside make_* calls, owner constructors, and deleters, not scattered through application logic. With custom deleters for C resources, make_* for heap objects, and factories at module boundaries, an application can contain zero raw new and delete, and the reviewer's job changes from auditing every exit path to checking that each acquisition is wrapped once, correctly.

Ownership across a factory boundaryFactorybodymake_unique<Config>(...)return byvalueelision ormoveCaller ownsStore orsharestd::move,orshared_ptrFactorybodymake_unique<Config>(...)return byvalueelision ormoveCaller ownsStore orsharestd::move,orshared_ptr
Ownership crossing a factory boundary: created inside, returned by elision or move, then stored or upgraded by the caller

The next lesson, "shared_ptr and the cost of shared ownership", answers what happens when one owner is not enough: how the control block counts owners, what the atomic counting costs on every copy, and when that price is worth paying.

Key takeaways

  • unique_ptr<T, D> takes the deleter as a type parameter; a stateless deleter keeps it 8 bytes on 64-bit Linux, a function-pointer deleter makes it 16
  • shared_ptr type-erases its deleter into the control block, so the deleter is not part of the type and sizeof stays 16 bytes
  • make_unique and make_shared remove raw new and are exception-safe regardless of the language standard; make_shared also merges object and control block into one allocation
  • A factory returns unique_ptr by value (elided or moved), and the caller can keep exclusive ownership or convert it to shared_ptr
Reflect
  1. Explain to a colleague, in two sentences: wrap a C resource (FILE*, malloc buffer, POSIX fd) in a smart pointer with the correct custom deleter
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close