19.7 Function: type erasure with a small buffer
A lambda in C++ has a unique, unnameable type. That is what lets the compiler inline it, and it is a problem the moment you want to store one: a vector of callbacks, a member that holds “something to call later”, a task queue. std::function solves it by type erasure, storing any compatible callable behind one type. This section builds a work-alike, Function<R(Args...)>, that keeps small callables inline in the object and spills large ones to the heap.
Concepts from other sections (1)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- task queue: the durable server’s routing key; only pollers of queue
agentreceiveAgentRuntasks. Read more: 10.8 The agent image and chart in Systems Engineering
Two independent ideas share one class, and it helps to keep them apart. Type erasure is about storing unrelated types behind one interface. The small buffer is purely a performance trick. You could have either without the other. Building both by hand, with a vtable written as a struct of function pointers, shows exactly what a virtual function call is and why inheritance would make the small buffer impossible. It builds on the move-only ownership of UniquePtr and the placement-new lifetime rules of Vector. The solution is the header function.hpp; main.cpp is the test suite.
Learning objectives
- Implement type erasure with a hand-written vtable of invoke, relocate, and destroy operations.
- Store small callables inline and decide, at compile time, which callables qualify.
- Relocate an inline callable correctly and keep the move constructor
noexceptfor every callable.- Constrain a forwarding constructor so it cannot hijack copying, and explain the cost of copyability in
std::function.
The interface
Section titled “The interface”| Member | Does |
|---|---|
Function(F&& f) | Erase any compatible callable |
operator()(args...) | Invoke, or throw bad_function_call if empty |
operator bool() | Whether it holds anything |
uses_inline_storage() | Exposed so the tests can prove the SBO works |
Move ctor / assign, swap | Transfer, handling both storage strategies |
Copy operations are deliberately deleted, so move-only callables (a lambda capturing a unique_ptr) can be stored. Every stored callable must be destroyed exactly once.
To build and run the tests from this directory:
c++ -std=c++20 -Wall -Wextra -O2 main.cpp -o function && ./function# ok cpp/08-function 49 checks passedA vtable by hand
Section titled “A vtable by hand”The vtable is written by hand, and it has to be. Inheritance would work and would force every callable onto the heap: a base subobject cannot live in a buffer whose type the base does not know. A struct of function pointers, built per callable type by make_vtable<Callable, Inline>(), gives the same dispatch with the storage decision left free.
Inline storage and relocation
Section titled “Inline storage and relocation”A callable goes inline only if it fits and its move cannot throw. Moving the Function has to relocate an inline callable, and if that move can throw there is no valid state to leave behind. The heap path has no such problem, because moving is then just copying a pointer, which is also why the move constructor can be noexcept for every callable.
Relocating an inline callable means calling its move constructor, not copying bytes. A callable may hold a pointer into itself, and even when it does not, memcpy on a non-trivially-copyable type is undefined. That is what move_to in the vtable is for.
Destruction must mirror construction exactly. An inline callable was placement-new’d, so only its destructor runs. A heap one came from a new-expression and needs the matching delete-expression, which also selects the correctly aligned operator delete for over-aligned types.
Why copying is deleted
Section titled “Why copying is deleted”Copying is deleted here, and std::function pays a real price for supporting it. A copyable erasure needs a fourth vtable entry and forces every stored callable to be copyable, which is why std::function<void()> f = [p = std::make_unique<int>(1)]{}; does not compile. C++23 added std::move_only_function for precisely this reason. test_move_only_capture shows what that buys.
Deriving the design
Section titled “Deriving the design”Six observations build the class.
One type must hold many types, so behaviour moves into data. Everything the Function will ever do to its callable is call it, relocate it, and destroy it. Capture those three operations as function pointers, generated per callable type, and store a pointer to that table.
The table is shared and immutable, so one static const VTable per callable type suffices; each Function holds just a pointer to it.
Storage is either a buffer inside the object or a heap pointer. A union of a 32-byte, max-aligned buffer and a void* holds one or the other, and the vtable records which.
Inline is allowed only when relocation is safe: the callable fits in size and alignment and its move constructor is noexcept.
Moving a Function depends on storage. For the heap, steal the pointer. For inline, move-construct into the destination buffer and destroy the source’s callable. Either way the source is left empty (vtable_ == nullptr).
Empty is vtable_ == nullptr. Calling an empty Function throws std::bad_function_call, like the standard one.
Building it step by step
Section titled “Building it step by step”The table and storage:
struct VTable { R (*invoke)(void* self, Args&&... args); void (*move_to)(void* from, void* to); // relocate between storages void (*destroy)(void* self); bool inline_storage;};
const VTable* vtable_ = nullptr; // nullptr means emptyunion { alignas(kBufferAlign) unsigned char buffer_[kBufferSize]; // 32 bytes void* heap_;};The converting constructor makes the storage decision once, at compile time:
template <typename F, typename = std::enable_if_t< !std::is_same_v<std::decay_t<F>, Function> && // not ourselves std::is_invocable_r_v<R, std::decay_t<F>&, Args...>>> // callable as R(Args...)Function(F&& f) { using Callable = std::decay_t<F>; constexpr bool fits = sizeof(Callable) <= kBufferSize && alignof(Callable) <= kBufferAlign && std::is_nothrow_move_constructible_v<Callable>;
static const VTable vt = make_vtable<Callable, fits>(); // one per type vtable_ = &vt;
if constexpr (fits) { ::new (static_cast<void*>(&buffer_)) Callable(std::forward<F>(f)); // placement new } else { heap_ = new Callable(std::forward<F>(f)); }}The generated operations. Each lambda without captures converts to a plain
function pointer, and knows the concrete Callable type:
template <typename Callable, bool Inline>static constexpr VTable make_vtable() { return VTable{ [](void* self, Args&&... args) -> R { return (*static_cast<Callable*>(self))(std::forward<Args>(args)...); }, [](void* from, void* to) { // Relocation by move construction, never memcpy. ::new (to) Callable(std::move(*static_cast<Callable*>(from))); }, [](void* self) { // Mirror construction: destructor only for placement new, // full delete-expression for new. if constexpr (Inline) { static_cast<Callable*>(self)->~Callable(); } else { delete static_cast<Callable*>(self); } }, Inline, };}Moving and calling:
Function(Function&& other) noexcept { if (other.vtable_) { vtable_ = other.vtable_; if (vtable_->inline_storage) { vtable_->move_to(&other.buffer_, &buffer_); // construct ours vtable_->destroy(&other.buffer_); // end theirs } else { heap_ = other.heap_; // steal the pointer other.heap_ = nullptr; } other.vtable_ = nullptr; // source is now empty }}
R operator()(Args... args) const { if (!vtable_) throw std::bad_function_call(); void* self = vtable_->inline_storage ? const_cast<void*>(static_cast<const void*>(&buffer_)) : heap_; return vtable_->invoke(self, std::forward<Args>(args)...);}Move assignment is reset() followed by the same logic. reset() calls
vtable_->destroy on whichever storage is active and nulls vtable_; the
destructor is just reset(). swap is three moves through a temporary.
The full solution is in function.hpp.
Why this design
Section titled “Why this design”A call is one indirect call through the vtable. Constructing a small callable allocates nothing; a large one allocates once. Each Function is 48 bytes on x86-64: an 8-byte vtable pointer, padding to the buffer’s 16-byte alignment, and the 32-byte buffer.
A virtual base class gives the same dispatch cost, but every callable must be heap-allocated as a derived object, so the small buffer becomes impossible. Templates all the way down (template <class F> void run(F f)) give zero overhead and inlining, but every caller and container must know the callable type. Erasure is for when one type must hold many.
What can go wrong
Section titled “What can go wrong”The enable_if on the converting constructor is not optional. Without it, Function(F&&) is a better match for a non-const Function& than any special member, so “copying” a Function would wrap it inside itself. The guard excludes std::decay_t<F> == Function.
| Mistake | Consequence |
|---|---|
| No guard on the forwarding constructor | A non-const Function& is wrapped inside a new Function |
| Inlining a callable with a throwing move | The noexcept move cannot be honoured |
memcpy to relocate the inline buffer | Self-pointers dangle; undefined for non-trivial types |
~Callable() plus operator delete for heap callables | Wrong deallocation function for over-aligned types |
Forgetting to null the source’s vtable_ | Both objects destroy the same callable |
| Inheritance-based erasure | Every callable is forced onto the heap |
Note:
operator()isconstbut calls the callable through a non-const pointer (theconst_cast), so a mutable lambda can change state through aconst Function&.std::functionhas the same wart, and the reference accepts it.
Where this leads
Section titled “Where this leads”Add copy support and watch the constraint propagate: the converting constructor now needs is_copy_constructible, and every test involving a move-only capture stops compiling. Then measure the buffer size against real code, because 32 bytes is a guess and the standard library implementations disagree with each other about the right answer. Type erasure is the run-time counterpart of the compile-time techniques in Expression templates and Graph with concepts.
Key terms
Section titled “Key terms”- Type erasure: hiding a concrete type behind a uniform interface so unrelated types can be stored as one type.
- Small buffer optimisation (SBO): storing small objects inside the owning object to avoid a heap allocation.
- Vtable: a table of function pointers used for dynamic dispatch, here written by hand.
- Placement new: constructing an object at a given address without allocating.
- Relocation: moving an object to a new address, done here by move construction plus destruction of the source.
Summary
Section titled “Summary”- A per-type
static const VTableholds invoke, relocate, and destroy, and eachFunctionstores a pointer to it. - Callables that fit in 32 bytes, are suitably aligned, and have
noexceptmoves are placement-new’d inline; others go on the heap. - Moving a
Functionrelocates inline callables with their move constructor and steals heap pointers, so it is alwaysnoexcept. - The forwarding constructor is guarded so it cannot capture a
Functionitself, and copying is deleted to support move-only callables. - Destruction mirrors construction: destructor only for inline, a delete-expression for heap.
Review questions
Section titled “Review questions”-
Why does the converting constructor exclude
std::decay_t<F> == Function?Answer
For a non-const
Function&argument, the forwarding template binds exactly and beats the deleted copy constructor (which needs a const conversion). It would then try to store aFunctioninside aFunction. The guard removes the template from overload resolution for that case. -
Why is a callable with a throwing move constructor forced onto the heap?
Answer
Moving an inline callable means move-constructing it into the destination. If that threw partway, the
Functionmove could not complete or roll back, and the move constructor is promisednoexcept. On the heap, a move is a pointer copy that cannot throw. -
Why can’t the move constructor
memcpythe inline buffer?Answer
The callable may contain pointers into itself or members with non-trivial moves (a
std::stringwith a small buffer, for instance). Copying bytes would leave those pointing into the old object, and is undefined for non-trivially-copyable types. Only its move constructor may relocate it. -
Why does
destroycalldeletefor heap callables instead of~Callable()plusoperator delete?Answer
The heap object was created with a new-expression, so the matching delete-expression both runs the destructor and selects the correct deallocation function, including the aligned one for over-aligned types.