Type erasure
What you will learn on this page
Section titled “What you will learn on this page”- What type erasure is: one value type that can hold and use objects of many unrelated types, chosen at run time, with no base class in the stored types.
- How to build one from a private interface and a model template, and why its copy, move, and assignment are written the way they are.
- What
std::functionandstd::anyerase, and what they keep. - How a small buffer avoids the heap for small objects, and what it takes to get right, using a hand-written table of functions.
- How a non-owning view erases the type without owning anything, and the lifetime rule it brings.
- What each form costs, counted, and when inheritance,
std::variant, or a template is the better choice.
The problem: a scene of shapes from different places
Section titled “The problem: a scene of shapes from different places”A drawing program shows a scene: a list of shapes, drawn in order, with a total area for the status bar. The shapes come from different places:
CircleandRectangleare small structs the team wrote, plain values.Pathis a larger class that owns a list of points.- More shapes are coming, some from other teams, who do not want to derive from a base class of ours, and from libraries whose types we cannot change at all.
The program also needs to copy the scene, to keep an undo snapshot, and the copy must not change when the scene does. Most shapes are tiny, and the scene is rebuilt often, so an allocation per tiny shape is a cost worth avoiding. And helper functions, such as one that draws a frame around a shape, should accept any shape without copying it.
Requirements
Section titled “Requirements”| # | Requirement | Design consequence |
|---|---|---|
| R1 | One list holds shapes of different types, and new types can be added | One type that can hold any shape, chosen at run time |
| R2 | Shape types need no common base class | The wrapper adapts each type; the types only need the operations |
| R3 | Copying the scene copies the shapes; the copy is independent | The wrapper has value semantics: copying it copies its shape |
| R4 | A failed copy of a shape, for example out of memory, changes nothing | The wrappers’ copy assignment gives the strong guarantee |
| R5 | Small shapes need no heap allocation | A second wrapper stores small shapes inside itself |
| R6 | Helpers take any shape without copying or allocating | A non-owning view type for parameters |
Step 1: what inheritance would need
Section titled “Step 1: what inheritance would need”The familiar design is an interface: an abstract Shape with virtual
draw and area, every shape derived from it, and a
std::vector<std::unique_ptr<Shape>> for the scene. That meets R1, and
it is the right design in many programs. Measured against the rest:
- R2 fails. Every shape must derive from
Shape. A library type cannot, so it needs a wrapper class that does. - R3 needs work. A vector of
unique_ptrcannot be copied. Copying needs a virtualcloneinShape, an override in every shape, and a copy loop. - R5 fails. Every shape is a separate heap object, as the performance page counted for particles.
- The scene holds pointers, not values. Code that uses it says
shape->draw(), and must think about who owns what.
Type erasure keeps the run-time choice of inheritance, and hides the inheritance inside one class, so that the rest of the program deals in values.
Step 2: what every shape provides
Section titled “Step 2: what every shape provides”Type erasure needs a fixed list of operations, as an interface does. Here it is written as a concept, which states what the wrappers need without asking for a base class:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// What every wrapper needs from a type: the two operations, called on a// const object. Nothing about a base class.// A C++20 concept is a named yes-or-no test on a type, checked by the// compiler. The `requires (...) { ... }` part lists expressions that must// compile for a type T: given a `const T& shape` and a `Canvas& canvas`,// `shape.draw(canvas)` must be valid, and `shape.area()` must be valid// and give something that converts to double. So Circle passes, and int// fails (an int has no draw). Nothing is run; only the code is checked.template <typename T>concept ShapeLike = requires(const T& shape, Canvas& canvas) { shape.draw(canvas); { shape.area() } -> std::convertible_to<double>;};
// The owning wrappers also copy what they hold. They refuse a DrawableRef:// owning a view would hide the fact that the viewed shape can die first.// The three parts, joined with && (all must hold): T is shape-like, T can// be copied, and T is not DrawableRef.template <typename T>concept StorableShape = ShapeLike<T> && std::copy_constructible<T> && !std::same_as<T, DrawableRef>;The shapes only have to provide those members:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Three shapes with no base class in common. Each has the two operations// a drawing needs, as const member functions; that is all type erasure// asks of them. Circle and Rectangle are plain values, so structs.// Default member values (= 1) mean Circle{} is a unit circle, and// Circle{2} sets the radius to 2.struct Circle { double radius = 1;
void draw(Canvas& canvas) const; [[nodiscard]] double area() const;};
struct Rectangle { double width = 1; double height = 1;
void draw(Canvas& canvas) const; [[nodiscard]] double area() const { return width * height; }};
// A corner of a Path. It is not a shape: it has no draw or area.struct Point { double x = 0; double y = 0;};
// A closed outline with a name. It owns heap memory, and at 56 bytes on// this site's compilers it is too big for SmallDrawable's buffer.class Path {public: // Takes the name and the points by value, and moves them into the // members, so a caller that passes temporaries pays for no extra copy. Path(std::string name, std::vector<Point> points);
void draw(Canvas& canvas) const; [[nodiscard]] double area() const; // of the polygon the points outline
private: std::string name_; // printed by draw, as in "path triangle ..." std::vector<Point> points_; // kept on the heap, so a copy allocates};Circle and Rectangle are structs, because they are plain values with
no rule tying their fields together. Path is a class with private
members, because its name and points are set once and read through its
operations. None of them knows that a drawing program will hold it in
a list of different types.
Step 3: an owning, copyable Drawable
Section titled “Step 3: an owning, copyable Drawable”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Holds any shape by value. Drawables of different shapes have one type,// so they can share a vector, and copying a Drawable copies its shape.// Costs: one heap allocation per shape held, and a virtual call per// operation. A moved-from Drawable is empty: it may be assigned to,// copied, or destroyed, but not drawn.class Drawable {public: // Implicit on purpose, like std::function: a Circle can be passed // wherever a Drawable is expected. The same_as test comes first, so // that copying a Drawable never asks whether Drawable is a shape. // // How it reads: `T&& shape` in a template is a forwarding reference. // It accepts anything; for a named Circle, T is `Circle&` (or // `const Circle&`), and for a temporary, T is `Circle`. // std::remove_cvref_t<T> strips the const and the & to give the plain // type, Circle, which is what the requires clause checks and what the // Model stores. std::forward<T>(shape) passes the argument on as it // came: a temporary is moved into the Model, a named shape is copied. // make_unique allocates the Model<Circle> on the heap, and self_ // owns it from then on. template <typename T> requires(!std::same_as<std::remove_cvref_t<T>, Drawable> && StorableShape<std::remove_cvref_t<T>>) Drawable(T&& shape) : self_(std::make_unique<Model<std::remove_cvref_t<T>>>(std::forward<T>(shape))) {}
// Copy: ask the model to clone itself, which makes a new Model holding // a copy of the shape. `?:` handles an empty (moved-from) source: its // copy is empty too, instead of calling clone through a null pointer. Drawable(const Drawable& other) : self_(other.self_ ? other.self_->clone() : nullptr) {} // Copy assignment: make the whole copy first, then swap it in. Drawable& operator=(const Drawable& other) { Drawable copy(other); // if this throws, *this is unchanged // Moving a unique_ptr cannot throw. self_ takes copy's model, and // self_'s old model is deleted; copy is left empty. self_ = std::move(copy.self_); return *this; } // Move: the unique_ptr's own move. The model stays where it is on the // heap; only the pointer changes hands, and the source is left null. Drawable(Drawable&&) noexcept = default; Drawable& operator=(Drawable&&) noexcept = default; // Destroying self_ deletes the Model, which destroys the shape in it. ~Drawable() = default;
// Each call goes through self_ to the virtual function of the Model // that was made for the real shape type. Not checked: calling either // on an empty (moved-from) Drawable dereferences a null pointer. void draw(Canvas& canvas) const { self_->draw(canvas); } [[nodiscard]] double area() const { return self_->area(); }
private: // The interface each stored shape is adapted to. It is private: users // of Drawable never see a base class or a pointer. // `= 0` makes each function pure virtual: Concept only says what // exists, and every Model must supply the code. The virtual // destructor makes deleting a Model through a Concept pointer run // Model's destructor, and so the shape's. struct Concept { virtual ~Concept() = default; virtual void draw(Canvas& canvas) const = 0; [[nodiscard]] virtual double area() const = 0; [[nodiscard]] virtual std::unique_ptr<Concept> clone() const = 0; };
// One Model per stored type, written by the compiler from this // template: an Adapter from T's members to the Concept interface. // `final` says nothing derives from Model. For T = Circle, the compiler // writes a Model<Circle> whose draw calls Circle::draw, and so on. template <typename T> struct Model final : Concept { explicit Model(const T& s) : shape(s) {} // copies the shape in explicit Model(T&& s) : shape(std::move(s)) {} // moves a temporary in
// `override` asks the compiler to check that each one really // replaces a virtual function of Concept. void draw(Canvas& canvas) const override { shape.draw(canvas); } [[nodiscard]] double area() const override { return shape.area(); } // Here the real type T is known, so the copy can be made: a new // Model<T> holding a copy of `shape`, returned as a Concept pointer. [[nodiscard]] std::unique_ptr<Concept> clone() const override { return std::make_unique<Model>(shape); }
T shape; // the shape itself, held by value inside the Model };
// The only data member: owns the one Model, or is null when empty. std::unique_ptr<Concept> self_;};How this code works: Drawable: what is made, copied, and moved
Follow three lines of code and watch the heap:
Drawable d = Circle{2};Drawable e = d;Drawable f = std::move(d);Drawable d = Circle{2};The template constructor runs withT = Circle, because the argument is a temporary.std::make_uniqueallocates oneModel<Circle>on the heap, andstd::forwardmoves the circle into itsshapemember.d.self_owns that model. From now on,dknows only that it has “someConcept”; the wordCircleappears nowhere ind’s type.d.draw(canvas), if it were called now, would followself_to the model and make a virtual call. The model is aModel<Circle>, so itsdrawruns, and that callsCircle::drawon the stored circle.Drawable e = d;The copy constructor asksd’s model tocloneitself.Model<Circle>::cloneknows the real type, so it allocates a secondModel<Circle>with a copy of the circle.eowns the second model. There are now two circles, and changing one cannot affect the other.Drawable f = std::move(d);The move constructor is theunique_ptr’s:f.self_takes the pointer andd.self_becomes null. No allocation, nothing copied, and the first model has not moved in memory.dis now empty: it may be assigned, copied (the copy is empty too), or destroyed, but not drawn.- At the end of the scope
f,e, anddare destroyed.fandeeach delete their model, which destroys its circle;dholds nothing and deletes nothing.
| After line | d |
e |
f |
Models on the heap |
|---|---|---|---|---|
Drawable d = Circle{2}; |
model 1 | (not yet made) | (not yet made) | 1 |
Drawable e = d; |
model 1 | model 2, a copy | (not yet made) | 2 |
Drawable f = std::move(d); |
empty | model 2 | model 1 | 2 |
The allocation test below checks exactly this count: two allocations,
for the first Drawable and the copy, and none for the move.
Text description of the diagram
Five boxes: Drawable, Concept, Model<T>, and two shapes, Circle and Path. Drawable has a private member self_, a unique
pointer to Concept, and public operations: a constructor from any
shape, draw, and area. Concept is an interface with three
abstract operations: draw, area, and clone. Model<T> is a
class template that implements Concept and holds a public member
shape of type T. Drawable owns zero or one Concept (zero
after being moved from). Model<T> implements Concept, and owns a
Circle when T is Circle, or a Path when T is Path;
Circle and Path know nothing about Drawable.
Diagram source (Mermaid)
classDiagram
class Drawable {
-self_ unique_ptr to Concept
+Drawable(shape)
+draw(canvas)
+area() double
}
class Concept {
<<interface>>
+draw(canvas)*
+area() double*
+clone() unique_ptr to Concept*
}
class Model~T~ {
+shape T
+draw(canvas)
+area() double
+clone() unique_ptr to Concept
}
class Circle
class Path
Drawable "1" *-- "0..1" Concept : self_
Concept <|.. Model~T~
Model~T~ *-- Circle : shape, when T is Circle
Model~T~ *-- Path : shape, when T is PathEach part, and why it is there:
Conceptis an interface, and it is private. The name is traditional for this technique and has nothing to do with the C++20conceptkeyword used forShapeLike. It lists the operations, plusclonefor copying. Nothing outsideDrawablecan name it, so no one can derive from it or hold aConcept*: the inheritance is an implementation detail.Model<T>is an Adapter written by the compiler. For each type aDrawableis constructed from, the compiler instantiatesModel<T>, which holds the shape by value and forwards each virtual call to the shape’s own member. The shape is not changed and does not know.cloneis Prototype’s copy. ADrawabledoes not know its shape’s type, so it asks the model to copy itself.Model<T>::clonedoes knowT, and copiesshape.- The constructor is a template, and implicit on purpose. A
Circlecan be passed wherever aDrawableis expected, as a lambda can be passed as astd::function. That is the value-semantic feel:scene.emplace_back(Circle{2}), nomake_unique, no->. It is constrained byStorableShape, soDrawable d = 42;does not compile. - The
same_astest comes first. Copying a non-constDrawablepasses aDrawable&. For that argument the template constructor, withT = Drawable&, is a better match than the copy constructor, which takesconst Drawable&, and aDrawablehasdrawandareatoo. Thesame_astest takes the template out of the choice. It must come first, because&&stops at the first false part: the compiler then never asks whetherDrawableis aStorableShape. Asking would mean checking whetherDrawablecan be copied, which means looking at this same constructor again. With theStorableShapepart alone, GCC 11.4 and Clang 14 both rejectedDrawable b = a;with an error about a constraint that depends on itself: the recursive constraint that C++ idioms alongside patterns warns about. - Copy assignment builds the copy first.
Drawable copy(other)may throw, while*thisis untouched; only then does*thistake the copy’s model, which cannot throw. That is the strong guarantee (R4), by the copy-and-swap reasoning of Exception safety. This holds for oneDrawable. Assigning a whole vector,scene = saved, gives only the basic guarantee: if a shape’s copy throws partway,sceneis valid but partly changed. To restore a scene with the strong guarantee, build the copy first and then move it in:scene = std::vector<Drawable>(saved);. - Move is the
unique_ptr’s move: no allocation, no throw. A moved-fromDrawableholds nothing. It can be assigned, copied, and destroyed, but callingdraworareaon it is undefined behaviour: it dereferences a null pointer. Callers cannot ask whether aDrawableis empty; a design that needs to would add anexplicit operator bool, asstd::functionhas.std::functionis safer here: calling an empty one throwsstd::bad_function_call. A moved-fromstd::functionis valid but unspecified by the standard; this site’s standard libraries leave it empty.
Using it
Section titled “Using it”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Different shapes, held by value in one vector.std::vector<Drawable> scene;scene.reserve(3); // room for three, so adding them never reallocates// emplace_back builds each Drawable in the vector from the shape given:// the Drawable's template constructor moves the temporary shape into a// new Model on the heap. No make_unique or pointer in sight.scene.emplace_back(Circle{2});scene.emplace_back(Rectangle{3, 4});// A Path called "triangle" through (0, 0), (4, 0), and (0, 3).scene.emplace_back(Path("triangle", {{0, 0}, {4, 0}, {0, 3}}));
// Each draw goes to the right shape's draw, through the hidden Model.Canvas canvas;for (const Drawable& shape : scene) shape.draw(canvas);draw_framed(scene[1], canvas); // a view of a Drawabledraw_framed(Circle{0.5}, canvas); // a view of a temporary, alive for the callfor (const std::string& command : canvas.commands()) std::cout << command << '\n';// std::fixed with std::setprecision(2) prints two decimal places;// std::defaultfloat switches back to the normal format afterwards.// total_area takes a span, and the vector converts to one.std::cout << "total area: " << std::fixed << std::setprecision(2) << total_area(scene) << std::defaultfloat << '\n';
// A copy is a separate value: changing the original leaves it alone.// Copying the vector copies each Drawable, and so clones each shape.const std::vector<Drawable> saved = scene;// The Rectangle becomes a temporary Drawable, which is then moved into// scene[0]; the old circle in scene[0] is destroyed. saved[0] keeps its// own copy of the circle.scene[0] = Rectangle{1, 1};std::cout << "area of scene[0]: " << scene[0].area() << ", of the saved copy: " << std::fixed << std::setprecision(2) << saved[0].area() << std::defaultfloat << '\n';The helper functions it calls, one taking a view and one a list of owned shapes:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Draws any shape between two frame lines. It only uses the shape during// the call, so it takes a view: no copy, no allocation, any shape type.void draw_framed(DrawableRef shape, Canvas& canvas);
// The total area of shapes held by value, of any mix of types.// std::span<const Drawable> is a view of a run of Drawables side by side,// such as a whole std::vector<Drawable>: it reads them in place, copying// none of them.[[nodiscard]] double total_area(std::span<const Drawable> shapes);circle radius 2rectangle 3 by 4path triangle through 3 pointsframe beginrectangle 3 by 4frame endframe begincircle radius 0.5frame endtotal area: 30.57area of scene[0]: 1, of the saved copy: 12.57
heap allocations Drawable SmallDrawable DrawableRefmake from a Circle 1 0 0make from a Path 2 2 0copy, Circle inside 1 0 0move, Path inside 0 0 0
in SmallDrawable's buffer: Circle yes, Rectangle yes, Path no- The scene holds a
Circle, aRectangle, and aPathin onestd::vector<Drawable>, and draws each. Their areas, 4π, 12, and 6, total 30.57. draw_framedwas given aDrawableand then a temporaryCircle. It takes aDrawableRef, a view, described in Step 6.- The saved copy still has the circle’s area, 12.57, after
scene[0]was replaced by a unit square: copying the vector copied the shapes (R3). - The allocation table is explained in Steps 5 and 6.
Step 4: type erasure in the standard library
Section titled “Step 4: type erasure in the standard library”The standard library has two type-erased types that every C++ program can use, and they show the range of the idea.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// std::function erases everything about a callable except one call.// std::function<void(Canvas&)> holds anything that can be called with a// Canvas& and returns nothing. Each lambda below keeps its own shape:// `[shape = Circle{1}]` makes a member of the lambda called shape and// starts it as Circle{1} (an init-capture). The two lambdas have different// types, but both fit in the same vector.LLD_TEST(std_function_erases_one_operation) { std::vector<std::function<void(Canvas&)>> drawers; drawers.emplace_back([shape = Circle{1}](Canvas& c) { shape.draw(c); }); drawers.emplace_back([shape = Rectangle{2, 2}](Canvas& c) { shape.draw(c); }); Canvas canvas; for (const auto& draw : drawers) draw(canvas); LLD_CHECK_EQ(canvas.commands().size(), std::size_t{2}); // There is no way to ask these for an area: only the call survived.}
// std::any erases everything: it keeps any copyable value, but offers no// operation on it until the exact type is named again.// std::any_cast has two forms. Given a pointer (&thing), it returns a// pointer to the value, or nullptr if the type is wrong. Given the any// itself, it returns the value (or a reference, with Circle&), and throws// std::bad_any_cast if the type is wrong. LLD_CHECK_THROWS(expression,// type) fails unless the expression throws that type.LLD_TEST(std_any_needs_the_exact_type_back) { std::any thing = Circle{2}; LLD_CHECK(std::any_cast<Circle>(&thing) != nullptr); // right type: a pointer LLD_CHECK(std::any_cast<Rectangle>(&thing) == nullptr); // wrong type: null LLD_CHECK_THROWS(std::any_cast<Rectangle>(thing), std::bad_any_cast); LLD_CHECK_EQ(std::any_cast<Circle&>(thing).radius, 2.0); // a reference into the any}std::function<R(Args...)>keeps one operation: calling withArgs.... It holds any copyable callable: a lambda, a function pointer, an object withoperator(). If a design needs one operation, it is the answer, and this page’sDrawablewould be overkill. Here it cannot answerarea: only the call survived.std::anykeeps the value’s type and what it needs to copy, move, and destroy the value, and no operation on the value itself. It can hold any copyable value: to use it, the code must name the exact type again withstd::any_cast, which fails for any other type. It suits passing a value through code that does not care what it is, and suits little else.- Allocation. Both may allocate. Implementations commonly store
small objects inside: on this site’s build machine
sizeofprinted 32 bytes for astd::function<void()>and 16 for astd::anywith both compilers. The standard does not say which objects are small enough.
Drawable sits between the two: it keeps exactly the operations a
shape needs, no more, as an interface would.
Step 5: a small buffer, for shapes that fit
Section titled “Step 5: a small buffer, for shapes that fit”Drawable allocates for every shape, even an eight-byte Circle (R5
fails). std::function avoids that for small callables by storing them
inside itself; SmallDrawable does the same for shapes. The idea is
called small-buffer optimization.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Like Drawable, but a shape that is small enough, and can be moved// without throwing, is stored inside the object itself, with no heap// allocation. Bigger shapes go on the heap, and the buffer holds a// pointer to them. Instead of virtual functions, each stored type gets a// table of plain function pointers that knows which kind of storage it// uses. (A Model<T> with virtual functions, built in the buffer, would// also work.) A moved-from SmallDrawable is empty, as with Drawable.class SmallDrawable {public: static constexpr std::size_t buffer_size = 32; // bytes kept inside the object
// True if a T is stored inside the buffer, false if it goes on the heap. // Three conditions: it fits in 32 bytes; it needs no stricter alignment // than the buffer has (std::max_align_t, enough for any ordinary type); // and its move constructor is noexcept. // Moving must not throw, so that SmallDrawable's own move cannot: a // std::vector of them then moves elements when it grows, instead of // copying them. // It is a variable template: SmallDrawable::stores_in_place<Circle> is // a bool worked out by the compiler for that one type. template <typename T> static constexpr bool stores_in_place = sizeof(T) <= buffer_size && alignof(T) <= alignof(std::max_align_t) && std::is_nothrow_move_constructible_v<T>;
// From any storable shape, implicitly, as for Drawable. First point ops_ // at the table for the plain shape type (Handler<Circle>::ops, say); // then let that type's create build the shape in the buffer, or on the // heap with a pointer in the buffer. std::forward moves a temporary // and copies a named shape, as in Drawable. template <typename T> requires(!std::same_as<std::remove_cvref_t<T>, SmallDrawable> && StorableShape<std::remove_cvref_t<T>>) SmallDrawable(T&& shape) : ops_(&Handler<std::remove_cvref_t<T>>::ops) { Handler<std::remove_cvref_t<T>>::create(storage_, std::forward<T>(shape)); }
// Copy: use the same table as the source, and ask it to copy the // source's shape into this buffer. A null table means the source is // empty, and then there is nothing to copy. If the copy throws, this // object was never finished, so its destructor does not run. SmallDrawable(const SmallDrawable& other) : ops_(other.ops_) { if (ops_ != nullptr) ops_->copy(other.storage_, storage_); } // Copy assignment: copy first, then move the copy in, as in Drawable. // The `this != &other` test skips self-assignment, `a = a`. SmallDrawable& operator=(const SmallDrawable& other) { if (this != &other) { SmallDrawable copy(other); // if this throws, *this is unchanged *this = std::move(copy); // the move assignment below; cannot throw } return *this; } // Move: std::exchange(other.ops_, nullptr) returns other's table pointer // and sets other's to null in one step. Null means "empty", so other's // destructor will not touch the shape any more. Then the table moves // the shape (or just its heap pointer) from other's buffer into ours. SmallDrawable(SmallDrawable&& other) noexcept : ops_(std::exchange(other.ops_, nullptr)) { if (ops_ != nullptr) ops_->move(other.storage_, storage_); } // Move assignment: destroy our own shape first (reset), then do what // the move constructor does. SmallDrawable& operator=(SmallDrawable&& other) noexcept { if (this != &other) { reset(); ops_ = std::exchange(other.ops_, nullptr); if (ops_ != nullptr) ops_->move(other.storage_, storage_); } return *this; } ~SmallDrawable() { reset(); } // destroys the shape, if there is one
// Every operation goes through the table. Like Drawable, these are // not checked: on an empty object ops_ is null. void draw(Canvas& canvas) const { ops_->draw(storage_, canvas); } [[nodiscard]] double area() const { return ops_->area(storage_); }
private: // What a virtual function table holds, written out: one per stored type. // Each member is a pointer to a function. `void (*draw)(const void*, // Canvas&)` reads "draw points to a function that takes a const void* // and a Canvas& and returns nothing". void* means "the address of // some bytes, type unknown": here, the buffer. struct Ops { void (*draw)(const void* storage, Canvas& canvas); double (*area)(const void* storage); void (*copy)(const void* from, void* to); // may throw void (*move)(void* from, void* to) noexcept; // leaves nothing in from to destroy void (*destroy)(void* storage) noexcept; };
// The functions for one stored type T. In place, the buffer holds the // T itself; otherwise it holds a T* to a heap object. // Everything is static: a Handler is never created; it is a box of // functions for one T. `if constexpr` is decided while compiling, so // each Handler<T> keeps only the branch for its own kind of storage. template <typename T> struct Handler { // The shape, from the buffer. In place: the buffer's address is the // shape's address. On the heap: the buffer holds a T*, so the inner // * (next to std::launder) reads that pointer, and the outer * follows // it to the shape. // std::launder: see the page; it gives a usable pointer to the // object that placement new built at that address. static const T& get(const void* storage) noexcept { if constexpr (stores_in_place<T>) { return *std::launder(static_cast<const T*>(storage)); } else { return **std::launder(static_cast<T* const*>(storage)); } }
// Builds a T from `shape` (copied or moved, as std::forward says). // `::new (storage) T(...)` is placement new: it allocates nothing, // and builds the object in memory we already have, the buffer. // On the heap path, the plain `new T(...)` allocates the shape, and // placement new then stores that T* in the buffer. If building the // shape throws, nothing has been stored. template <typename U> static void create(void* storage, U&& shape) { if constexpr (stores_in_place<T>) { ::new (storage) T(std::forward<U>(shape)); } else { ::new (storage) T*(new T(std::forward<U>(shape))); } }
static void draw(const void* storage, Canvas& canvas) { get(storage).draw(canvas); } static double area(const void* storage) { return get(storage).area(); } // A copy is a new shape made from the old one: in the other buffer, // or a new heap object. May throw if T's copy throws. static void copy(const void* from, void* to) { create(to, get(from)); }
// In place: build a new T in `to` from the old one, then end the old // one's life by calling its destructor, `source.~T()`, by hand. The // bytes of `from` are then just bytes again. Cannot throw, because // only types with a noexcept move are stored in place. static void move(void* from, void* to) noexcept { if constexpr (stores_in_place<T>) { T& source = *std::launder(static_cast<T*>(from)); ::new (to) T(std::move(source)); source.~T(); } else { // Only the pointer moves; the shape stays where it is. ::new (to) T*(*std::launder(static_cast<T**>(from))); } }
// In place: run the destructor by hand (the buffer itself is part // of the SmallDrawable and is not freed). On the heap: delete the // shape the stored pointer points to. static void destroy(void* storage) noexcept { if constexpr (stores_in_place<T>) { std::launder(static_cast<T*>(storage))->~T(); } else { delete *std::launder(static_cast<T**>(storage)); } }
// The table for T, filled in by the compiler: one per type, shared // by every SmallDrawable that holds a T. static constexpr Ops ops{&draw, &area, ©, &move, &destroy}; };
// Destroys the shape, if any, and marks this object empty. void reset() noexcept { if (ops_ != nullptr) { ops_->destroy(storage_); ops_ = nullptr; } }
const Ops* ops_ = nullptr; // null when empty // 32 raw bytes inside the object: they hold a shape or a T*. alignas // puts the array on an address that suits any ordinary type. alignas(std::max_align_t) std::byte storage_[buffer_size];};How this code works: SmallDrawable, in place and on the heap
A SmallDrawable is two things side by side: ops_, a pointer to a
table of functions, and storage_, 32 bytes of raw memory. What the
bytes mean depends on the table.
Storing a Circle (8 bytes, noexcept move):
SmallDrawable a = Circle{1};runs the template constructor withT = Circle. It setsops_ = &Handler<Circle>::ops, the table the compiler built for circles.Handler<Circle>::createchecksstores_in_place<Circle>, which is true, so it uses placementnewto build the circle insidestorage_. No heap memory is used.a.area()callsops_->area(storage_), which isHandler<Circle>::area. Itsgettreats the buffer’s address as the circle’s address, and callsCircle::area.SmallDrawable b = std::move(a);first takesa.ops_withstd::exchange, leavinga.ops_null, soais now empty. ThenHandler<Circle>::movebuilds a new circle inb.storage_from the old one and calls the old one’s destructor by hand. Exactly one circle exists afterwards, inb.
Storing a Path (56 bytes, too big):
SmallDrawable p = path;setsops_ = &Handler<Path>::ops.stores_in_place<Path>is false, socreatedoesnew Path(...), a heap allocation, and stores only the resultingPath*in the first bytes ofstorage_.p.area()callsHandler<Path>::area, whosegetreads the pointer out of the buffer and follows it: two*s instead of one.- Moving
pcopies just that pointer into the new buffer. ThePathstays where it is on the heap, which is why the move allocates nothing. - Destroying the
SmallDrawablecallsHandler<Path>::destroy, whichdeletes the heapPath.
Empty. ops_ == nullptr is the only sign of “empty”. The copy and
move constructors, move assignment, and reset all check it before
using the table. draw and area do not, so calling them on a
moved-from object is undefined behaviour, as with Drawable.
Why the move must clear the source first. If b took the table
pointer but a.ops_ kept it, both destructors would call destroy.
For a circle that destroys the same object twice; for a Path it
deletes the same heap object twice. The failure list below includes
exactly that mistake.
Reading it in order:
- The storage is a byte buffer, 32 bytes, aligned for any ordinary
type. A shape is stored in place if it fits, its alignment is
supported, and its move constructor is
noexcept. Otherwise the shape goes on the heap and the buffer holds a pointer to it.stores_in_place<T>is public so that tests can check the choice. - Why the
noexceptrule. Moving aSmallDrawablemoves its in-place shape. Its move constructor is one function for every stored type, so itsnoexceptcannot depend on the shape: the shape’s type is erased. It promises never to throw, so only shapes that move without throwing may go in the buffer. The promise matters because astd::vector<SmallDrawable>moves its elements when it grows only if their move cannot throw; otherwise it copies them. A shape whose move may throw is stored on the heap, where a move only copies a pointer.std::anyfollows the same rule: the standard lets it store a value inside itself only if the value’s move cannot throw. - A table of function pointers replaces the virtual functions.
Each stored type
Thas one constant table,Handler<T>::ops, built by the compiler, and theSmallDrawableholds a pointer to it. Each function takes the buffer and knows, fromT, whether the shape is in it or behind a pointer. This is what a compiler’s virtual table holds, written out. It is one choice, not the only one: the buffer could instead hold aModel<T>, built there with placementnew, and be used through aConcept*to it. The table was chosen here because it shows every operation in one place, and the buffer then holds only the shape, without a model’s hidden virtual-table pointer. std::launderturns a pointer to the buffer into a pointer to the shape that placementnewbuilt there. A cast alone is not enough. The buffer is an array ofstd::byte, which provides storage for the shape, but a byte of it and the shape are not pointer-interconvertible, so the cast still points to the byte.std::launderreturns a pointer to the object that lives at that address. The alternative is to keep the pointer that placementnewreturned, at the cost of storing one more pointer.- The special members are written by hand, because the buffer holds
raw bytes that the compiler cannot copy correctly. The copy
constructor asks the table to copy; the move
constructor takes the source’s table pointer with
std::exchange, which marks the source empty, and then asks the table to move the shape; the destructor asks it to destroy. Copy assignment builds a copy first, for the strong guarantee, as inDrawable. Move assignment destroys its own shape, then moves.
All of this is a precise use of object lifetime rules, and it is easy to get slightly wrong in ways that still pass simple tests. Changed copies of the example were tested to see what the tests catch:
- Forgetting to destroy the source after an in-place move: two checks of the lifetime test failed, because the count of live small shapes was two too high: each in-place move left one extra shape, once in a move constructor and once inside a copy assignment, which moves its copy in.
- Forgetting to
deletea heap shape indestroy: one check failed, and AddressSanitizer’s leak checker reported the leaked shapes. - Copy assignment that destroys its old shape before copying: the exception test failed, because a failed copy left the target empty.
- A move constructor that does not mark the source empty: AddressSanitizer reported a heap use after free, because both objects then destroyed the same heap shape.
The lifetime test counts live objects of a small and a big shape type through moves, copies, and assignments:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Moves and assignments with both kinds of storage, including a = a.LLD_TEST(small_drawable_moves_shapes_in_place_and_on_the_heap) { SmallDrawable in_place = Circle{3}; // in the buffer SmallDrawable on_heap = Path("p", {{0, 0}, {2, 0}, {2, 2}, {0, 2}}); // a 2 by 2 square SmallDrawable a = std::move(in_place); // the circle is moved buffer to buffer SmallDrawable b = std::move(on_heap); // only the pointer to the Path moves LLD_CHECK_EQ(drawn(a), std::string("circle radius 3")); LLD_CHECK_EQ(b.area(), 4.0); in_place = Rectangle{1, 2}; // a moved-from object can be assigned on_heap = std::move(a); // on_heap, empty after its move, now takes the circle LLD_CHECK_EQ(in_place.area(), 2.0); LLD_CHECK_EQ(drawn(on_heap), std::string("circle radius 3")); // `same` is another name for on_heap, so the next line assigns the // object to itself: the case the `this != &other` test is there for. SmallDrawable& same = on_heap; on_heap = same; // assigning an object to itself must leave it intact LLD_CHECK_EQ(drawn(on_heap), std::string("circle radius 3"));}
// A smoke test: 20 shapes, alternating a circle (in place) and a Path (on// the heap), make the vector grow and move its elements several times.// The total proves every shape survived the moves. Expected: ten unit// circles (10 pi) and ten triangles of area 0.5.LLD_TEST(small_drawables_grow_in_a_vector) { std::vector<SmallDrawable> shapes; for (int i = 0; i < 20; ++i) { if (i % 2 == 0) { shapes.emplace_back(Circle{1}); } else { shapes.emplace_back(Path("p", {{0, 0}, {1, 0}, {1, 1}})); } } double total = 0; for (const SmallDrawable& shape : shapes) total += shape.area(); const double expected = 10 * std::numbers::pi + 10 * 0.5; LLD_CHECK(total > expected - 1e-9 && total < expected + 1e-9);}
// Counted<N> (defined above, not shown) is a shape that adds 1 to a// counter in every constructor and takes 1 away in its destructor, so// `alive` is the number that exist right now. N bytes of padding set its// size: 8 fits the buffer, 64 does not. A missed destroy leaves the count// too high; a double destroy makes it too low.LLD_TEST(every_stored_shape_is_destroyed_exactly_once) { using Small = Counted<8>; using Big = Counted<64>; static_assert(SmallDrawable::stores_in_place<Small> && !SmallDrawable::stores_in_place<Big>); { // an inner scope: a, b, c, and d are destroyed at its closing brace SmallDrawable a = Small{}; // the temporary Small is moved in and dies SmallDrawable b = Big{}; // a new heap Big is built from the temporary SmallDrawable c = std::move(a); // a Small moves in place SmallDrawable d = std::move(b); // only a Big's pointer moves a = d; // a copy of the Big b = c; // a copy of the Small c = std::move(a); // c's Small is destroyed; c takes a's Big LLD_CHECK_EQ(Small::alive, 1); // in b LLD_CHECK_EQ(Big::alive, 2); // in c and d } // Every shape is gone once the four wrappers are destroyed. LLD_CHECK_EQ(Small::alive, 0); LLD_CHECK_EQ(Big::alive, 0);}How this code works: Counting the shapes in the lifetime test
Small (8 bytes) is stored in place and Big (64 bytes) on the heap.
The counts after each line of the inner block (written here without
the SmallDrawable in front), which the checks then confirm:
| Line | What happens | Small::alive |
Big::alive |
|---|---|---|---|
a = Small{} |
the temporary is moved into a’s buffer, then the temporary dies |
1 | 0 |
b = Big{} |
a heap Big is built from the temporary, which then dies |
1 | 1 |
c = std::move(a) |
a new Small is built in c, and a’s is destroyed |
1 | 1 |
d = std::move(b) |
only the pointer moves to d |
1 | 1 |
a = d |
copy assignment copies the Big onto the heap and moves the pointer into a |
1 | 2 |
b = c |
copy assignment copies the Small, then moves it into b’s buffer and destroys the copy’s |
2 | 2 |
c = std::move(a) |
c destroys its Small, then takes a’s Big pointer |
1 | 2 |
| end of the block | the three that hold a shape (b, c, d) destroy it; a is empty |
0 | 0 |
At the end, b holds the last Small, c and d hold the two
Bigs, and a is empty. If any path forgot to destroy a shape, a
count would stay above 0; if a shape were destroyed twice, a count
would go below the expected value.
The first test moves and assigns both kinds of storage, including an assignment to itself. The growth test is a smoke test: it fills a vector past several reallocations and checks the total, which catches crashes and sanitizer reports, but would not notice a copy where a move was meant. The lifetime test is the one that counts.
Step 6: a view, for parameters
Section titled “Step 6: a view, for parameters”draw_framed uses a shape during the call and keeps nothing. Taking a
const Drawable& would force callers with a plain Circle to build a
Drawable, with an allocation, just to call it. Taking a template
parameter would put draw_framed in a header and compile it for each
shape type. A view erases the type without owning anything:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Refers to any shape without owning or copying it, as std::string_view// refers to text: a pointer to the object and a pointer per operation.// Making one never allocates. The shape must outlive the DrawableRef, so// use it for parameters, not for members that outlive the call.class DrawableRef {public: // From any shape-like object, implicitly. T is the shape's own type // (`const T&` takes no ownership and makes no copy). The same_as test // leaves copying a DrawableRef to the ordinary copy constructor, which // copies the three pointers. // The constructor stores: // - object_: the shape's address. std::addressof is & that cannot be // fooled by a type that overloads operator&. Stored as a const void*, // the type is forgotten here. // - draw_ and area_: one small function each. A lambda with nothing in // its [] (no captures) can be turned into a plain function pointer. // Each lambda is written inside this template, so it still knows T, // and static_cast<const T*> turns the void* back into a T pointer. template <typename T> requires(!std::same_as<T, DrawableRef> && ShapeLike<T>) DrawableRef(const T& shape) noexcept : object_(std::addressof(shape)), draw_([](const void* object, Canvas& canvas) { static_cast<const T*>(object)->draw(canvas); }), area_([](const void* object) -> double { return static_cast<const T*>(object)->area(); }) {}
// Call the stored function, handing it the stored address. void draw(Canvas& canvas) const { draw_(object_, canvas); } [[nodiscard]] double area() const { return area_(object_); }
private: // Not owned: nothing is freed when the view goes away. const void* object_; void (*draw_)(const void* object, Canvas& canvas); double (*area_)(const void* object);};How this code works: DrawableRef: a view through three pointers
Take Rectangle rectangle{1, 1}; and const DrawableRef view = rectangle;.
- The constructor runs with
T = Rectangle. It stores the rectangle’s address inobject_as aconst void*: an address with no type attached. From here on, the view does not know it is looking at a rectangle. - It stores two function pointers. Each comes from a lambda with an
empty capture list, and such a lambda converts to a plain function
pointer. Because the lambdas are written inside the template, the
compiler makes a fresh pair for
Rectangle, and inside themTstill meansRectangle. That is where the type is remembered: in the code, not in the data. view.area()callsarea_(object_). The function made forRectanglecasts theconst void*back toconst Rectangle*and callsRectangle::areaon the rectangle itself.- Nothing was copied. If the code then sets
rectangle.width = 5,view.area()returns 5, because it reads the same object. The view test checks exactly that.
The cast back in step 3 is safe only because the same template both
stored the address and wrote the function that casts it back, so the
two always agree on T. What the view cannot check is whether the
rectangle is still alive: that is the caller’s job, as the flawed
example below shows.
- Three pointers, 24 bytes: the object, and one function per
operation. The functions are captureless lambdas, which convert to
plain function pointers; each one knows
Tand casts thevoid*back. - It never allocates, and never copies the shape. It sees the object itself, so a change to the object shows through the view.
- It can view anything shape-like, including a
Drawableor aSmallDrawable, which are shapes too. It is passed by value, likestd::string_view. - The owning wrappers refuse it.
StorableShapeexcludesDrawableRef, because aDrawablethat owned a view would look like a safe value while depending on another object’s lifetime. This is a guard against one mistake, not a guarantee: a shape that holds a raw pointer or a reference to another object can still be stored, and has the same problem.
What each form costs
Section titled “What each form costs”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Prints a table of heap allocations: one row per operation, one// column per wrapper. Two helpers, defined above main, do the work:// allocations_in(make) runs the lambda `make` and returns how many// times the global operator new was called while it ran, and row// prints one line of the table. Each lambda captures by reference// ([&]), builds one wrapper `d`, and calls area so that it is used;// `(void)` throws away the [[nodiscard]] result on purpose.const Circle circle{1};const Path square("square", {{0, 0}, {1, 0}, {1, 1}, {0, 1}});std::cout << "\n";row("heap allocations", std::string("Drawable"), std::string("SmallDrawable"), std::string("DrawableRef"));row("make from a Circle", allocations_in([&] { const Drawable d(circle); (void)d.area(); }), allocations_in([&] { const SmallDrawable d(circle); (void)d.area(); }), allocations_in([&] { const DrawableRef d(circle); (void)d.area(); }));row("make from a Path", allocations_in([&] { const Drawable d(square); (void)d.area(); }), allocations_in([&] { const SmallDrawable d(square); (void)d.area(); }), allocations_in([&] { const DrawableRef d(square); (void)d.area(); }));
// Made outside the counted lambdas, so that only the copy is counted.const Drawable owning_circle(circle);const SmallDrawable small_circle(circle);const DrawableRef view_circle(circle);row("copy, Circle inside", allocations_in([&] { const Drawable d(owning_circle); (void)d.area(); }), allocations_in([&] { const SmallDrawable d(small_circle); (void)d.area(); }), allocations_in([&] { const DrawableRef d(view_circle); (void)d.area(); }));
// Not const, because they are moved from. Path does not fit the buffer,// so both owning forms hold it on the heap, and a move passes a pointer.Drawable owning_square(square);SmallDrawable small_square(square);DrawableRef view_square(square); // "moving" a view just copies its pointersrow("move, Path inside", allocations_in([&] { const Drawable d(std::move(owning_square)); (void)d.area(); }), allocations_in([&] { const SmallDrawable d(std::move(small_square)); (void)d.area(); }), allocations_in([&] { const DrawableRef d(std::move(view_square)); (void)d.area(); }));
// Which shapes SmallDrawable keeps in place, from its own rule.std::cout << "\nin SmallDrawable's buffer: Circle " << (SmallDrawable::stores_in_place<Circle> ? "yes" : "no") << ", Rectangle " << (SmallDrawable::stores_in_place<Rectangle> ? "yes" : "no") << ", Path " << (SmallDrawable::stores_in_place<Path> ? "yes" : "no") << '\n';The table in the output above counts heap allocations for each operation, with the counter from the performance page:
- Making one from a
Circle:Drawableallocates its model;SmallDrawablestores the circle in place; the view allocates nothing. - Making one from a
Path: both owning forms copy the path, which allocates for its points, and put it on the heap: two allocations each. The 56-bytePathdoes not fit the 32-byte buffer. - Copying: a
Drawableclones, so it allocates again; aSmallDrawablewith a circle copy-constructs the circle in its own buffer, with no allocation, assmall_shapes_stay_in_the_small_drawablechecks. A shape that owns heap memory of its own, such as a longstd::string, would still allocate for that memory when copied. - Moving: no allocation for any of them. A heap shape’s pointer moves; an in-place shape’s move constructor builds it in the new buffer.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST(name) defines one test, and LLD_CHECK_EQ(actual, expected)// records a failure, printing both values, if they differ (from the// site's test header, lld_test.hpp). heap::AllocationCounter counts calls// to the global operator new from the moment it is created; count()// gives the number so far. Each test makes its shapes first, so only// the wrappers' own allocations are counted.
// Drawable: one Model allocated for a, one for the copy b, none for the move.LLD_TEST(drawable_allocates_once_per_shape_and_per_copy) { const Circle circle{1}; heap::AllocationCounter counter; Drawable a = circle; // allocates a Model<Circle> const Drawable b = a; // clone: allocates a second Model const Drawable c = std::move(a); // takes a's pointer: no allocation LLD_CHECK_EQ(counter.count(), std::size_t{2}); // a and b; the move took a's LLD_CHECK_EQ(b.area(), c.area());}
// SmallDrawable with small shapes: making, copying, moving, and both kinds// of assignment all stay in the buffers, so nothing is allocated.LLD_TEST(small_shapes_stay_in_the_small_drawable) { const Circle circle{1}; const Rectangle rectangle{2, 3}; heap::AllocationCounter counter; SmallDrawable a = circle; // the circle is copied into a's buffer SmallDrawable b = a; // copied into b's buffer SmallDrawable c = std::move(a); // moved into c's buffer; a is now empty b = rectangle; // becomes a temporary SmallDrawable, which is moved in c = b; // copy assignment: c now holds a 2 by 3 rectangle LLD_CHECK_EQ(counter.count(), std::size_t{0}); LLD_CHECK_EQ(c.area(), 6.0);}
// A Path is too big for the buffer: making one allocates, moving does not.LLD_TEST(large_shapes_go_on_the_heap_and_moves_do_not_copy_them) { const Path path("p", {{0, 0}, {1, 0}, {1, 1}}); heap::AllocationCounter made; SmallDrawable a = path; LLD_CHECK_EQ(made.count(), std::size_t{2}); // the Path, and its vector of points heap::AllocationCounter moved; // a second counter, for the move alone const SmallDrawable b = std::move(a); LLD_CHECK_EQ(moved.count(), std::size_t{0}); // only the pointer moved LLD_CHECK_EQ(b.area(), 0.5); // a right triangle with sides 1 and 1}
// A view of the Path, and a copy of the view: three pointers each, no heap.LLD_TEST(a_view_never_allocates) { const Path path("p", {{0, 0}, {1, 0}, {1, 1}}); heap::AllocationCounter counter; const DrawableRef a = path; const DrawableRef b = a; LLD_CHECK_EQ(b.area(), 0.5); LLD_CHECK_EQ(counter.count(), std::size_t{0});}The allocation tests turn the table into checks, so that a change that adds an allocation fails a test. Each call through any of the three forms is an indirect call that the compiler usually cannot inline, which matters only in loops hot enough to measure.
Testing
Section titled “Testing”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Compile-time checks: static_assert stops the build if its condition is// false, so these are proved by the build itself, before any test runs.// std::constructible_from<A, B> asks "can an A be made from a B?".static_assert(ShapeLike<Circle> && ShapeLike<Rectangle> && ShapeLike<Path>);static_assert(!ShapeLike<int> && !ShapeLike<std::string>);static_assert(std::constructible_from<Drawable, Circle>);static_assert(!std::constructible_from<Drawable, int>);// The owning wrappers refuse a view, and every wrapper is itself a shape.static_assert(!std::constructible_from<Drawable, DrawableRef>);static_assert(!std::constructible_from<SmallDrawable, DrawableRef>);static_assert(ShapeLike<Drawable> && ShapeLike<SmallDrawable> && ShapeLike<DrawableRef>);// Both owning wrappers promise that moving them cannot throw.static_assert(std::is_nothrow_move_constructible_v<Drawable>);static_assert(std::is_nothrow_move_constructible_v<SmallDrawable>);
// Where SmallDrawable keeps each shape. SlowMove is a test shape (defined// above, not shown) that is small but whose move is not noexcept.static_assert(SmallDrawable::stores_in_place<Circle>);static_assert(SmallDrawable::stores_in_place<Rectangle>);static_assert(!SmallDrawable::stores_in_place<Path>); // too bigstatic_assert(!SmallDrawable::stores_in_place<SlowMove>); // small, but its move may throwVerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure// if the condition is false; LLD_CHECK_EQ(actual, expected) records one,// printing both values, if they differ. They come from lld_test.hpp.// drawn(shape), a helper defined above (not shown), draws a shape on a// fresh Canvas and returns the first command it recorded, such as// "circle radius 2".
// Changing the original after a copy leaves the copy as it was.LLD_TEST(a_copy_of_a_drawable_is_a_separate_value) { Drawable original = Circle{2}; const Drawable copy = original; original = Rectangle{1, 1}; LLD_CHECK_EQ(drawn(original), std::string("rectangle 1 by 1")); LLD_CHECK_EQ(drawn(copy), std::string("circle radius 2"));}
LLD_TEST(one_vector_holds_different_shapes) { std::vector<Drawable> shapes; shapes.emplace_back(Circle{1}); shapes.emplace_back(Rectangle{2, 3}); shapes.emplace_back(Path("t", {{0, 0}, {4, 0}, {0, 3}})); // pi for the unit circle, 6 for the rectangle, 6 for the triangle. // Floating-point sums may be off in the last digits, so the check // allows a tiny distance (1e-9) instead of testing ==. const double expected = std::numbers::pi + 6 + 6; LLD_CHECK(total_area(shapes) > expected - 1e-9 && total_area(shapes) < expected + 1e-9);}
// After a move, `a` is empty. Copying it gives another empty Drawable, and// assigning a new shape makes it usable again. Drawing it while empty// would be undefined behaviour, so the test never does.LLD_TEST(a_moved_from_drawable_can_be_assigned_and_copied) { Drawable a = Circle{1}; const Drawable b = std::move(a); const Drawable empty_copy = a; // NOLINT: copying the moved-from value is allowed a = Rectangle{2, 2}; LLD_CHECK_EQ(a.area(), 4.0); LLD_CHECK_EQ(drawn(b), std::string("circle radius 1"));}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A failed copy leaves both objects as they were: the strong guarantee.// Fragile (defined above, not shown) is a shape whose copy constructor// throws std::runtime_error while Fragile::fail_copies is true. Its move// never throws, so SmallDrawable keeps it in place. LLD_CHECK_THROWS(// expression, type) fails unless the expression throws that type.LLD_TEST(a_failed_copy_assignment_changes_nothing) { SmallDrawable source = Fragile{7}; SmallDrawable target = Circle{1}; Drawable owning_source = Fragile{8}; Drawable owning_target = Circle{2}; Fragile::fail_copies = true; // from here on, copying a Fragile throws // Each assignment must copy the Fragile, so each one throws. LLD_CHECK_THROWS(target = source, std::runtime_error); LLD_CHECK_THROWS(owning_target = owning_source, std::runtime_error); Fragile::fail_copies = false; // back to normal for the rest of the tests // The targets still hold their circles, and the sources their Fragiles. LLD_CHECK_EQ(drawn(target), std::string("circle radius 1")); LLD_CHECK_EQ(drawn(source), std::string("fragile 7")); LLD_CHECK_EQ(drawn(owning_target), std::string("circle radius 2")); LLD_CHECK_EQ(drawn(owning_source), std::string("fragile 8"));}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The view holds the rectangle's address, so a later change shows through.LLD_TEST(a_view_sees_the_object_itself_not_a_copy) { Rectangle rectangle{1, 1}; const DrawableRef view = rectangle; rectangle.width = 5; // changes the rectangle, not the view LLD_CHECK_EQ(view.area(), 5.0);}
// draw_framed's DrawableRef parameter accepts an owning Drawable and a// plain temporary Rectangle alike. The temporary lives until the end of// the full expression, so it is alive for the whole call.LLD_TEST(draw_framed_takes_any_shape) { Canvas canvas; const Drawable owning = Circle{1}; draw_framed(owning, canvas); // a view of a Drawable, which is itself a shape draw_framed(Rectangle{2, 3}, canvas); // a view of a temporary const std::vector<std::string> expected{"frame begin", "circle radius 1", "frame end", "frame begin", "rectangle 2 by 3", "frame end"}; LLD_CHECK(canvas.commands() == expected);}- The compile-time checks confirm what may be stored and where:
the shapes satisfy the concept,
intdoes not, the owning wrappers refuse a view, both owning wrappers move without throwing, and the in-place rule putsPathand a shape with a throwing move on the heap. - The value tests check R1 and R3: one vector holds three different
shapes and totals their areas, a copy is unaffected by a change to
the original, and a moved-from
Drawablecan be assigned and copied. - The exception test makes a shape’s copy throw, and checks that both the source and the target of a failed assignment are unchanged (R4), for both owning wrappers.
- The view tests check that a view sees the object itself, and that
draw_framedaccepts aDrawableand a temporary.
The tests run with GCC and Clang and under AddressSanitizer and
UndefinedBehaviorSanitizer, which is where lifetime mistakes in
SmallDrawable show up. In the tsan build only the main tests run; the
demo and the allocation tests replace operator new, which Clang’s
ThreadSanitizer runtime also defines.
The design at a glance
Section titled “The design at a glance”class drawing::Drawable
owns a copy of any StorableShape; 8 bytes
Data members
std::unique_ptr<Concept> self_;Concept and Model<T> are private
Member functions
Drawable(T&& shape);implicit; one heap allocationDrawable(const Drawable& other);clones the shapeDrawable& operator=(const Drawable& other);strong guaranteeDrawable(Drawable&&) noexcept;leaves other emptyvoid draw(Canvas& canvas) const;double area() const;
class drawing::SmallDrawable
owns; in place if small, else on the heap; 48 bytes
Data members
const Ops* ops_;one table of functions per stored typestd::byte storage_[buffer_size];the shape, or a pointer to it
Member functions
static constexpr std::size_t buffer_size = 32;static constexpr bool stores_in_place<T>;SmallDrawable(T&& shape);implicitSmallDrawable(const SmallDrawable& other);SmallDrawable(SmallDrawable&& other) noexcept;leaves other emptyvoid draw(Canvas& canvas) const;double area() const;
class drawing::DrawableRef
views a shape it does not own; 24 bytes
Data members
const void* object_;void (*draw_)(const void*, Canvas&);double (*area_)(const void*);
Member functions
DrawableRef(const T& shape) noexcept;implicit; the shape must outlive the viewvoid draw(Canvas& canvas) const;double area() const;
Choosing a way to hold different types
Section titled “Choosing a way to hold different types”| You have | Prefer | Why |
|---|---|---|
| A fixed set of types you own | std::variant and std::visit |
Usually no allocation; calls can often be inlined; adding an operation is easy |
| Types you own that share data or behaviour, used by reference | An interface and derived classes | Simple and familiar; objects with identity are not values |
| One operation, such as a callback | std::function |
Already written and tested |
| An open set of types, used as values, with a few operations | A type-erased wrapper like Drawable |
Value semantics, no base class in the stored types |
| The same, with many small objects, after measuring | A small-buffer wrapper like SmallDrawable |
No allocation for small objects |
| A parameter used only during the call | A view like DrawableRef, or a template |
No copy, no allocation |
| The type known where it is used | A template | No erasure needed; Generic programming |
Type erasure does not remove the costs of run-time polymorphism; it
moves them inside one class, so that the rest of the program deals in
values. Its own cost is code: three versions of every operation (in the
wrapper, the interface, and the model) and special members that must be
exactly right. A design with two or three shape types that one team
owns is simpler with std::variant. Composition-based alternatives to
inheritance-heavy patterns
compares these alternatives for patterns.
Common mistakes
Section titled “Common mistakes”- An under-constrained converting constructor. In a scratch copy
whose constructor was constrained only by
ShapeLike, copying a non-constDrawablecompiled, chose the template, and wrapped theDrawableinside a new one: two allocations instead of one, with both compilers, and a copy that is not the same kind of object. Without thesame_astest but withStorableShape, the copy does not compile at all, as Step 3 explains. - A copy that is not deep. Holding the model in a
std::shared_ptrmakes copying cheap, but the copies share one shape, so R3 breaks as soon as a shape can change. A shared, immutable model is a valid design, but it should be a decision, documented as such. - Copy assignment that destroys before it copies. If the copy throws, the object is left empty, as the mutation above showed.
- Small-buffer storage for types whose move can throw, which makes the wrapper’s move throw and turns vector growth into copying.
- Forgetting
std::launder, or the destructor call, after placementnew. A missing destructor call shows up in a counting test, as the mutation above did. A missingstd::launderis undefined behaviour that nothing here detects: a copy of the example with everystd::launderremoved passed all its tests with both compilers, at-O0and-O2, and under both sanitizers. It can still break with another compiler or optimizer. Keep such code small and reviewed. - Storing a view. A
DrawableRefmember, or one returned from a function, usually outlives what it refers to. - Type erasure for a closed set of types. If every type is known and
owned,
std::variantdoes the job with less code. - An ever-growing interface. Every operation is written three times; if the list keeps growing, the abstraction is probably wrong.
When the requirements change
Section titled “When the requirements change”- “Add a
boundsoperation.” Add it toShapeLike,Concept,Model,Drawable,SmallDrawableand its table, the view, and every shape. The compiler finds every place, because a shape without it no longer satisfiesShapeLike. - “Shapes can hold a
std::unique_ptrand cannot be copied.” This conflicts with R3: a scene of such shapes cannot be copied for undo, so undo needs another plan, such as recording the commands that changed the scene. If that is accepted, make a move-only wrapper: dropclone, the copy constructor, and copy assignment, and relaxStorableShapeto ask forstd::move_constructibleinstead ofstd::copy_constructible. C++23’sstd::move_only_function, in the callout in Step 4, made the same decision for callables. - “Thousands of shapes of only three types, drawn every frame.” Use
a
std::variant, or a separate vector per type, as the performance page did for particles; measure first. - “A plug-in, compiled separately, supplies new shapes.” Type erasure works across a plug-in boundary only if both sides agree on the wrapper’s layout and table, which is an ABI question. PImpl, ABI, versioning, and compatibility covers it.
Exercise
Section titled “Exercise”Exercise: Compare with inheritance
A colleague proposes the inheritance design from Step 1:
// An abstract base class: every shape derives from it and overrides the// two pure virtual (= 0) functions. The virtual destructor makes deleting// a shape through a Shape pointer destroy the whole derived object.class Shape {public: virtual ~Shape() = default; virtual void draw(Canvas& canvas) const = 0; [[nodiscard]] virtual double area() const = 0;};// The scene owns each shape through a unique_ptr, one heap object each.using Scene = std::vector<std::unique_ptr<Shape>>;This code is illustrative and was not compiled as shown; the answer was compiled.
- The program must copy the scene for undo. What must be added to the
inheritance design, and where? What does
Drawableneed? - A library type
vendor::Spritehasrender(Canvas&) constandcovered() constinstead ofdrawandarea, and cannot be changed. What does each design need? - Count the heap allocations to build a scene of ten circles and to
copy it, in each design, with
reservecalled first. Which design allocates less? - Name two situations in which the inheritance design is the better choice.
Show the explained answer
-
Inheritance:
std::unique_ptrcannot be copied, soShapeneeds avirtual std::unique_ptr<Shape> clone() const, every derived class must override it, and the scene needs a copy function that clones each element:// A deep copy of the scene: a new heap object for every shape.Scene copy_of(const Scene& scene) {Scene copy;copy.reserve(scene.size()); // one allocation for the vector itself// `shape` is a const unique_ptr<Shape>&. shape->clone() is the// virtual call that makes a copy of the real derived type and// returns it as a new unique_ptr<Shape>, which push_back moves in.for (const auto& shape : scene) copy.push_back(shape->clone());return copy;}Shapeis abstract, so no one can copy aShape&into a plainShapeby mistake. The remaining hole is assignment through references:*scene[0] = *scene[1]runs onlyShape’s assignment and leaves the derived parts unchanged, even when the two shapes are of different types. SoShapeshould make its copy assignmentprotected, or delete it if derived classes need no assignment. Its copy constructor can beprotectedtoo;clonein a derived class can still use it.Drawable: nothing;cloneis written once, inModel<T>, andstd::vector<Drawable>is copied with=. -
Both need an adapter, because the names differ. For inheritance, a class
SpriteShape : public Shapeholding avendor::Sprite, and overridingdraw,area, andclone. ForDrawable, a plain struct holding avendor::Spritewithdrawandareamembers, and no base class orclone. The difference is smaller than it first looks; it grows with the number of such types. -
The same: in a scratch program built with GCC 11.4 and Clang 14 and the example’s allocation counter, both designs made 11 allocations to build (the vector, then one per circle) and 11 to copy. Type erasure by itself is not cheaper than inheritance; it moves the allocation inside.
SmallDrawablewould make one allocation for each, the vector’s, because a circle fits in place. -
For example:
- The objects have identity, not value: widgets in a window tree, with parents and children that refer to each other. Copying them makes no sense, and type erasure’s value semantics buy nothing.
- The types are yours and share data or behaviour that belongs in a base class, or are extended by deriving, as in a framework.
- The interface is large: twenty operations written three times each is a lot of code to keep in step.
- Readers and debuggers should see a plain class hierarchy; type erasure’s machinery is unfamiliar to many developers.
Summary
Section titled “Summary”- Type erasure gives one value type that holds and uses any type with the right operations, chosen at run time, without a base class in the stored types.
- Inside, it is a private interface, a model template that
adapts each type to it, and
clonefor copying; the inheritance never appears in the public interface. std::functionerases all but one call,std::anyerases everything; a hand-written wrapper keeps exactly the operations a design needs.- A small buffer avoids allocations for small objects, at the cost of size and delicate lifetime code. A view avoids ownership entirely, and must not outlive what it views.
- Copy assignment should build the copy first, for the strong guarantee, and moves should not throw.
- Prefer
std::variantfor closed sets, inheritance for objects with identity, and templates when the type is known; use type erasure for open sets of value types.