
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
Custom deleters: one owner, any cleanup function
4 min readThe 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 a callable (function pointer, lambda, or struct with operator()) that a smart pointer invokes on the managed resource instead of the default delete 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:
#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:
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:
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:
#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)
}
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.
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.
make_unique, make_shared, and the exception-safety argument
3 min readEverything 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:
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:
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:
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 storing a callable of any type behind a uniform interface, here inside the heap-allocated control block, so the pointer type does not depend on it 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.
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.
Factory functions: returning ownership, deleting new/delete for good
3 min readA a function that creates a resource and returns it already wrapped in an owning smart pointer, hiding the acquisition and cleanup details from callers 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:
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:
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.
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
- 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
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- 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
- Man pagefopen(3): open a stream
- Man pagemalloc(3): allocate dynamic memory
- Man pageopen(2): open a file
- Man pageclose(2): close a file descriptor
Official documentation first. Links checked when the lesson was published.