C++ idioms alongside patterns - RAII, PImpl, type erasure, policy-based design
What you will learn on this page
Section titled “What you will learn on this page”- What an idiom is, and how it differs from a design pattern.
- Four C++ idioms you will meet inside almost every pattern written in C++: RAII, PImpl, type erasure, and policy-based design.
- For each one: the problem it solves, how it works in a small compiled example, which pattern it resembles and why it is not that pattern, and what it costs.
- How to choose between them and the simpler tools around them.
Idioms and patterns
Section titled “Idioms and patterns”A design pattern names a recurring arrangement of collaborating roles: an interface and its implementations, a subject and its observers, a context and its strategy. It is described in terms of classes and objects, so the same pattern can be written in C++, Java, or C#, with the same roles.
An idiom is a recurring way of writing something in one language, using rules that language has. RAII depends on C++ destructors running at a known point. PImpl depends on C++ incomplete types and header files. Type erasure and policy-based design depend on C++ templates. Move the code to a language without those rules and the idiom either disappears or turns into something else.
The difference matters for design discussions:
- Idioms are smaller. A pattern shapes how several classes work together; an idiom shapes how one class or one function is written.
- Idioms are often how a pattern is implemented in C++. An
Observer’s subscription can be an RAII handle; a Strategy can be a
template policy; a Command can be stored through type erasure, in
std::function. - Calling an idiom a pattern, or the other way round, leads to comparing the wrong things. “Should we use PImpl or Bridge?” mixes a build-time technique with a design decision about two things that vary.
The patterns overview places idioms below the classic patterns for this reason: the patterns lean on them for ownership, lifetime, and genericity.
The idiom map
Section titled “The idiom map”Text description of the diagram
A flowchart with four rows, one per idiom. Row one: the problem “a resource must be released on every path out of a scope” leads to RAII, which the standard library uses in std::unique_ptr, std::lock_guard, std::fstream, and std::vector; RAII has no close pattern. Row two: “private members in a header force recompiles and expose details” leads to PImpl, common in library classes that keep a stable binary interface; PImpl resembles Bridge with one hidden implementation. Row three: “unrelated types must be stored and used as one type, by value” leads to type erasure, used in std::function and std::any; it is built from an interface, an Adapter per type, and Prototype’s clone. Row four: “a class’s behaviour must be chosen when the code is compiled” leads to policy-based design, used in unique_ptr’s deleter, std::map’s comparison, allocators, and std::char_traits; it resembles Strategy chosen at compile time.
Diagram source (Mermaid)
flowchart LR
P1["A resource must be released<br/>on every path out of a scope"] --> RAII["RAII"]
P2["Private members in a header<br/>force recompiles and expose details"] --> PIMPL["PImpl"]
P3["Unrelated types must be stored<br/>and used as one type, by value"] --> TE["Type erasure"]
P4["A class's behaviour must be<br/>chosen when the code is compiled"] --> PBD["Policy-based design"]
RAII --> S1["std::unique_ptr, std::lock_guard,<br/>std::fstream, std::vector"]
PIMPL --> S2["common in library classes<br/>that keep a stable binary interface"]
TE --> S3["std::function, std::any"]
PBD --> S4["unique_ptr's deleter, std::map's comparison,<br/>allocators, std::char_traits"]
RAII -.->|"no close pattern"| G1["none"]
PIMPL -.->|"resembles"| G2["Bridge, with one hidden implementation"]
TE -.->|"is built from"| G3["an interface, an Adapter per type,<br/>and Prototype's clone"]
PBD -.->|"resembles"| G4["Strategy, chosen at compile time"]The example
Section titled “The example”One small report program uses all four. It builds rows of cells of different types, writes them as CSV and as plain text, aligns them in a table, and saves the CSV to a temporary file:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Different types in one row: each converts to a Cell.// A table is a vector of rows, and a row is a vector of Cells. The inner// braces are one row each. Label{"item"} makes a Label, and because// Cell's constructor is not `explicit`, the compiler turns it into a// Cell where the vector expects one. The first row is the header.const std::vector<std::vector<Cell>> rows{ {Label{"item"}, Label{"price"}, Label{"change"}}, {Label{"kettle"}, Money{2499}, Percent{5}}, {Label{"lamp, desk"}, Money{1250}, Percent{-10}},};Each idiom has one class: TempFile (RAII), TableFormatter (PImpl),
Cell (type erasure), and RowWriter (policy-based design).
class TempFile
RAII: owns one open C file; move-only
Data members
std::unique_ptr<std::FILE, Close> file_;owned; closed by the deleter
Member functions
TempFile();opens; throws std::runtime_errorvoid write(std::string_view text);std::string read_all();
class TableFormatter
PImpl: the header shows only a pointer; move-only
Data members
std::unique_ptr<Impl> impl_;owned; Impl is defined in table.cpp
Member functions
TableFormatter();~TableFormatter();defined where Impl is completevoid add_row(std::vector<std::string> row);throws std::invalid_argumentstd::string render() const;
class Cell
type erasure: any CellValue, held by value; copyable
Data members
std::unique_ptr<Concept> self_;owned; points at a Model<T>
Member functions
Cell(T value);template, for any CellValue TCell(const Cell& other);deep copy through clonestd::string text() const;
class RowWriter<Format>
policy-based design: Format chosen at compile time
Data members
std::string text_;owned
Member functions
void add(const std::vector<Cell>& cells);const std::string& text() const;
RAII: release on every path
Section titled “RAII: release on every path”The problem
Section titled “The problem”A C library gives you a std::FILE* from std::tmpfile() and expects
you to call std::fclose exactly once. Every early return, every
exception, and every forgotten branch is a chance to leak the handle
or close it twice.
The idiom
Section titled “The idiom”Resource Acquisition Is Initialization: an object acquires the
resource in its constructor and releases it in its destructor. C++
runs the destructor of every fully constructed local object when its
scope ends, by return, by exception, or by reaching the closing
brace, so the release cannot be skipped, provided the exception is
caught somewhere; an uncaught exception, std::exit, or std::abort
may end the program without running destructors.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// RAII: the constructor acquires a C file handle, and the destructor (here,// the unique_ptr's deleter) releases it on every path out of the scope.// TempFile writes no destructor, copy, or move of its own (the "rule of// zero"): the unique_ptr member makes it move-only and closes the file.class TempFile {public: // Opens a new temporary file, which the system removes when it is closed. // Throws std::runtime_error if it cannot be created. TempFile();
// Appends text. Throws std::runtime_error if it cannot be written. void write(std::string_view text);
// Everything written so far. Throws std::runtime_error on a read error. std::string read_all();
private: // The deleter: what the unique_ptr calls instead of `delete` when it // lets go of a non-null pointer. A FILE* from <cstdio> must be // released with std::fclose, never with delete. operator() makes a // Close object callable like a function. The result of fclose is // ignored, because a destructor has no good way to report it. struct Close { void operator()(std::FILE* file) const noexcept { std::fclose(file); } }; // The second template argument names the deleter type. The unique_ptr // owns the open file: exactly one TempFile holds it at a time. std::unique_ptr<std::FILE, Close> file_; // never null, unless moved from};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// std::tmpfile opens a new file for reading and writing, or returns// nullptr if it cannot. The unique_ptr takes ownership of the pointer at// once, in the member initializer, so there is no moment when the file// is open but not owned.TempFile::TempFile() : file_{std::tmpfile()} { // Refuse to construct a TempFile without a file, so every TempFile that // exists holds an open one. Nothing leaks: the unique_ptr holds nullptr, // and the deleter is not called for a null pointer. if (!file_) { throw std::runtime_error{"TempFile: cannot create a temporary file"}; }}
// Appends at the end of the file, wherever the last read left the file// position.void TempFile::write(std::string_view text) { if (text.empty()) { return; // nothing to write: do not touch the file at all } // Seeking is required between reading and writing the same C stream. // file_.get() lends the raw FILE* to the library function without giving up // ownership. fseek(..., 0, SEEK_END) moves to 0 bytes from the end. if (std::fseek(file_.get(), 0, SEEK_END) != 0) { throw std::runtime_error{"TempFile: cannot go to the end"}; } // fwrite writes text.size() items of 1 byte each and returns how many it // wrote; anything less than all of them is a failure. if (std::fwrite(text.data(), 1, text.size(), file_.get()) != text.size()) { throw std::runtime_error{"TempFile: write failed"}; }}
// Reads the whole file from the start, 256 bytes at a time. Not const,// because reading moves the file position.std::string TempFile::read_all() { std::FILE* file = file_.get(); // borrowed: the unique_ptr still owns it if (std::fseek(file, 0, SEEK_SET) != 0) { // also ends any writing throw std::runtime_error{"TempFile: cannot go back to the start"}; } std::string text; std::array<char, 256> chunk{}; std::size_t count = 0; // fread fills up to 256 bytes of chunk and returns how many it read. The // assignment inside the condition stores that count and tests it: the // loop stops when a read returns 0, at the end of the file or on an // error. Only the first `count` bytes of chunk are appended. while ((count = std::fread(chunk.data(), 1, chunk.size(), file)) > 0) { text.append(chunk.data(), count); } // A read of 0 does not say which it was; ferror tells an error apart // from a normal end of file. if (std::ferror(file) != 0) { throw std::runtime_error{"TempFile: read failed"}; } return text;}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The braces make a scope: `file` lives from its declaration to the// closing brace, and its destructor runs there however the block ends.{ TempFile file; // opened here file.write(csv.text()); const std::string back = file.read_all(); std::cout << "read back from a temporary file: " << (back == csv.text() ? "the same text" : "different text") << '\n';} // closed here, and so removed, also if something above throws and is caught further up- The class writes no destructor. The
std::unique_ptrmember with aClosedeleter does the release, soTempFilefollows the rule of zero: the compiler’s destructor and moves are correct, and the copy operations are deleted becausestd::unique_ptrcannot be copied. Two copies would close one file twice. - The constructor throws if it cannot acquire. A
TempFilethat exists always holds an open file, so its member functions do not check for a null handle. The one exception is a moved-fromTempFile, which may only be assigned to or destroyed. read_allis notconst. Reading moves the file position, so the function changes the object’s state and says so.writeseeks back to the end before it appends, because C requires a seek between reading and writing the same stream.
Not a pattern, and what it costs
Section titled “Not a pattern, and what it costs”RAII has no roles, no interface, and no collaborating classes; it is a rule about one object’s lifetime. That is why it is an idiom. It is also the foundation that makes the patterns’ ownership safe in C++: the Object Pool’s lease and an Observer’s subscription handle are both RAII.
It costs almost nothing at run time. Its main limit is that a
destructor should not throw, so errors during release are lost:
std::fclose can fail when it flushes buffered data, and Close
ignores the result. A class whose release can fail in a way the caller
must hear about should also offer an explicit close() that reports
the error, and keep the destructor as the backstop. The RAII
page covers the idiom in depth.
PImpl: keep private members out of the header
Section titled “PImpl: keep private members out of the header”The problem
Section titled “The problem”Every file that includes a class’s header sees its private members, and must be recompiled when they change, even though it cannot use them. For a class included in hundreds of files, or shipped in a library whose users should not have to recompile, that is a real cost.
The idiom
Section titled “The idiom”Pointer to implementation: the class holds only a pointer to a struct that its header declares but does not define:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// PImpl: the header shows only a pointer to an incomplete Impl, so the// private data can change without recompiling the code that includes this.// TableFormatter collects rows of text and lays them out in aligned// columns. Everything it stores lives in Impl, which this header never// defines.class TableFormatter {public: TableFormatter(); // Only declared here. Destroying the unique_ptr<Impl> deletes the Impl, // and that needs Impl's full definition, which only table.cpp has. ~TableFormatter(); // defined in table.cpp, where Impl is complete TableFormatter(TableFormatter&&) noexcept; TableFormatter& operator=(TableFormatter&&) noexcept; // Not copyable: declaring the moves stops the compiler generating copies.
// Throws std::invalid_argument if the row is empty, or has a different // number of columns from the first row. Takes the row by value, so a // caller can move a vector in; a refused row leaves the table unchanged. void add_row(std::vector<std::string> row);
// Each column padded to its widest entry (counted in bytes), two spaces // apart, one line per row, with no trailing spaces. std::string render() const;
private: // Declared, not defined: Impl is an incomplete type here. A pointer to // an incomplete type is allowed, which is the whole trick. struct Impl; std::unique_ptr<Impl> impl_; // never null, unless moved from};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The private data, defined only in this file. Changing these members// recompiles table.cpp alone, not the files that include table.hpp.struct TableFormatter::Impl { std::vector<std::vector<std::string>> rows; std::vector<std::size_t> widths; // the widest entry in each column};
// Each TableFormatter puts its own Impl on the heap, owned by impl_.TableFormatter::TableFormatter() : impl_{std::make_unique<Impl>()} {}// `= default` here, after Impl's definition, so the compiler can write// the code that deletes an Impl. The two moves just move impl_ across.TableFormatter::~TableFormatter() = default;TableFormatter::TableFormatter(TableFormatter&&) noexcept = default;TableFormatter& TableFormatter::operator=(TableFormatter&&) noexcept = default;
// Checks the row, works out the new column widths in a copy, and only then// stores both. Every step that could throw (the vector copy and resize,// and push_back, which leaves rows as it was if it throws) comes before// widths is replaced, so a throw leaves the table as it was.void TableFormatter::add_row(std::vector<std::string> row) { // Refuse an empty row. Once the table has rows, widths has one entry // per column, so a row of a different size is refused too. The first // row may have any size of at least 1; it sets the column count. if (row.empty() || (!impl_->rows.empty() && row.size() != impl_->widths.size())) { throw std::invalid_argument{"TableFormatter: every row needs the same number of columns"}; } std::vector<std::size_t> widths = impl_->widths; // changed only once the row is stored // For the first row, widths is empty and grows to one 0 per column; for // later rows it already has that size, and resize changes nothing. widths.resize(row.size(), 0); // Each column's width is the longest text seen so far in that column. for (std::size_t i = 0; i < row.size(); ++i) { widths[i] = std::max(widths[i], row[i].size()); } impl_->rows.push_back(std::move(row)); // move the strings in, no copy impl_->widths = std::move(widths); // cannot throw: a vector move}VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Used like any other class: nothing here can see the Impl or its members.TableFormatter table;for (const std::vector<Cell>& row : rows) { // The table stores text, so turn each Cell of the row into a string. std::vector<std::string> texts; for (const Cell& cell : row) { texts.push_back(cell.text()); } // add_row takes its row by value. std::move hands over the vector's // contents instead of copying them; texts is not used again. table.add_row(std::move(texts));}std::cout << "aligned:\n" << table.render();How this code works: TableFormatter::add_row
add_row keeps one number per column, widths: the length of the
longest text seen so far in that column. It works on a copy of
widths and changes the table only at the end, so a row that throws
changes nothing.
- Check. An empty row is refused. Once the table has a row, a row with a different number of columns is refused too.
- Copy and grow. For the first row, the copy is empty, and
resizegives it one 0 per column. Later rows already have the right size. - Widen. Each column takes the larger of its old width and this row’s entry.
- Store. The row and the new widths are moved into the
Impl.
With the three rows from main.cpp (lengths counted in characters):
| Row added | Entry lengths | widths after |
|---|---|---|
item, price, change |
4, 5, 6 | 4, 5, 6 |
kettle, 24.99, +5% |
6, 5, 3 | 6, 5, 6 |
lamp, desk, 12.50, -10% |
10, 5, 4 | 10, 5, 6 |
render (in table.cpp, not shown) then writes each entry, and after
every entry except the last in a row, width - length + 2 spaces. So
item is followed by 10 - 4 + 2 = 8 spaces, and kettle by 6, which
lines up price, 24.99, and 12.50 in the output below.
- The destructor and moves are declared in the header and defaulted
in the
.cppfile, whereImplis complete. Declaring the destructor stops the compiler generating moves, so they must be declared too.std::unique_ptrneeds the complete type to delete it. The Bridge page shows what goes wrong otherwise. - The class is move-only. Declaring the move operations stops the
compiler from generating copies. Write the copies by hand, in the
.cppfile, if the class must be copyable. - A moved-from object has no
Impl. Use it only to assign to or destroy. constdoes not reach theImpl. Inrender() const, the pointer isconstbut theImplis not, so the compiler would accept a change toimpl_->rows. Reviewconstfunctions by hand, or wrap the pointer in a wrapper that passesconstthrough, such as the experimentalstd::experimental::propagate_const.
Resembles Bridge, but is not Bridge
Section titled “Resembles Bridge, but is not Bridge”The shape is Bridge’s: a class people use, holding a pointer to a separate implementation. The purpose is different. Bridge separates two things that vary independently, behind an interface with several implementations. PImpl has exactly one implementation, no interface, and no variation; it exists to hide details and shorten builds. The classic description of Bridge calls this one-implementation form a degenerate Bridge; it is still worth keeping apart, because PImpl’s purpose is build times and hiding details, not two things that vary.
It costs a heap allocation per object, an extra indirection on every call, and functions the compiler cannot inline across the boundary (without link-time optimization). Use it for classes included in many files whose private members change often, or for a library that must keep its binary interface stable. Do not use it for small value types or classes used in one place. PImpl, ABI, versioning, and compatibility covers the binary-interface side.
Type erasure: unrelated types, one value type
Section titled “Type erasure: unrelated types, one value type”The problem
Section titled “The problem”A report row holds a price, a percentage, and a label. These are unrelated value types:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Three unrelated value types. None has a base class or a virtual function.struct Money { int cents = 0;};
struct Percent { int value = 0;};
struct Label { std::string text;};
// One free function per type turns it into text. Overloading picks the// right one from the argument's type. Money holds whole cents, so 2499// is shown as "24.99".std::string to_text(Money money); // "24.99", "-0.50"std::string to_text(Percent percent); // "+5%", "-10%", "0%"std::string to_text(const Label& label); // the text as it isThe classic answer is a base class CellBase with a virtual text(),
and a std::vector<std::unique_ptr<CellBase>>. That forces every value
type to inherit from the report’s base class, turns values into
pointers that cannot be copied without a clone, and puts a
std::make_unique in every row.
The idiom
Section titled “The idiom”Type erasure keeps the types unrelated and hides the inheritance inside one class:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Any copyable type with a to_text function. The to_text check comes first,// so that checking Cell itself stops there instead of asking whether Cell is// copyable while its copy constructor is being chosen.// Read the requires block as: "given a `const T& value`, the expression// to_text(value) must compile, and its result must convert to a// std::string". `&&` then adds a second condition: `T` can be copied.template <typename T>concept CellValue = requires(const T& value) { { to_text(value) } -> std::convertible_to<std::string>;} && std::copy_constructible<T>;
// Type erasure: holds a value of any CellValue type, by value, behind one// non-template interface. Callers see neither a base class nor a pointer.// How it works: Concept (below) is a private interface, Model<T> wraps a// `T` and implements it, and Cell holds a unique_ptr<Concept> that points at// some Model<T>. Cell's own functions just forward through that pointer.class Cell {public: // A constructor template: one constructor for each type `T` that meets // CellValue. It takes the value by value (copied, or moved from a // temporary), then moves it into a new Model<T> on the heap. This is the only place that knows `T`; after it // runs, the Cell holds only a pointer to the Concept interface, and `T` // has been "erased" from the Cell's type. template <CellValue T> Cell(T value) : self_{std::make_unique<Model<T>>(std::move(value))} {} // implicit, like std::function
// Copying asks the stored Model to clone itself, so the new Cell gets its // own copy of the value (a deep copy), not a second pointer to it. Cell(const Cell& other) : self_{other.self_->clone()} {} Cell& operator=(const Cell& other) { // clone() runs first. If it throws, self_ has not been touched yet. // If it succeeds, assigning the new unique_ptr deletes the old // Model. This also makes `a = a` safe: the clone is made before the // old value is deleted. self_ = other.self_->clone(); // copy first, so a throw changes nothing return *this; } // Moving just moves the pointer: no allocation, no copy of the value. // The moved-from Cell is left with a null self_. Cell(Cell&&) noexcept = default; Cell& operator=(Cell&&) noexcept = default; ~Cell() = default;
// Do not call text() on, or copy from, a moved-from Cell; assign to it // or destroy it instead. // A virtual call: it runs the text() of whichever Model<T> is stored. std::string text() const { return self_->text(); }
private: struct Concept { // the interface every stored type is adapted to virtual ~Concept() = default; virtual std::string text() const = 0; virtual std::unique_ptr<Concept> clone() const = 0; };
// The adapter: it stores a `T` and answers the Concept functions by // calling the free function to_text on it. Writing Model<Money> in the // constructor above is what makes the compiler generate this struct // for Money. template <typename T> struct Model final : Concept { // one per stored type, made by the compiler explicit Model(T v) : value{std::move(v)} {} std::string text() const override { return to_text(value); } // Inside Model<T>, plain `Model` means Model<T>. make_unique copies // `value` into a new Model of the same type, and the result converts // to a unique_ptr to the base, Concept. std::unique_ptr<Concept> clone() const override { return std::make_unique<Model>(value); } T value; };
std::unique_ptr<Concept> self_; // owned; never null, unless moved from};Conceptis a private interface: the operations every stored type must support.Model<T>is a private class template the compiler instantiates once for each stored type. It holds the value and implementsConceptby callingto_text(value), soMoneyneeds no base class and no virtual function.Cellis what callers see: an ordinary value type, which can be copied, assigned, and stored in astd::vectorby value. The constructor is a template that accepts anyCellValue, and is notexplicit, so aMoneyconverts to aCellwhere one is expected, asstd::functionaccepts any callable.- Copying is deep. The copy constructor calls
clone, so eachCellowns its own value:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A Cell behaves like an int or a std::string: copies are independent.const Cell price = Money{2499};Cell copy = price; // a deep copy: its own Money// Percent{5} first becomes a temporary Cell, which is then moved into// copy; the Money that copy held is destroyed. price is untouched.copy = Percent{5}; // now holds a different typestd::cout << "the original keeps its value: " << price.text() << ", the copy now holds: " << copy.text() << '\n';How this code works: Cell
A Cell holds one pointer, self_, to a Concept. What it really
points at is a Model<T> for whichever type was stored. Here is what
each line of the snippet above does:
const Cell price = Money{2499};The template constructor runs withT = Money. It allocates aModel<Money>holdingMoney{2499}and stores its address inprice.self_. From here on, nothing inprice’s type mentionsMoney.Cell copy = price;The copy constructor callsprice.self_->clone(). That is a virtual call, so it runsModel<Money>::clone, which allocates a secondModel<Money>with a copy of the value. Now there are twoMoneyobjects, one in each cell.copy = Percent{5};The right side is not aCell, so the compiler first builds a temporaryCellfrom it, which allocates aModel<Percent>. That temporary is moved intocopy:copy.self_takes the new pointer, and the oldModel<Money>it held is deleted.pricestill points at its ownModel<Money>.text()on each cell is a virtual call throughself_:price.text()reachesModel<Money>::text, which callsto_text(Money)and returns"24.99";copy.text()reachesModel<Percent>::textand returns"+5%".
Copy assignment between two cells, as in a = b in the tests, works
the same way as step 2: b’s model is cloned first, and only then is
a’s old model deleted, so a failed clone leaves a unchanged and
a = a is safe.
Built from patterns, but not one of them
Section titled “Built from patterns, but not one of them”Inside, type erasure is an interface (Concept), an Adapter for each
stored type (Model<T> adapts to_text to the interface), and
Prototype’s clone for copying. What makes it an idiom is the C++
part: the compiler writes the adapters from a template, and the
inheritance never appears in the public interface.
It costs one heap allocation per Cell here, and a virtual call per
text(). Library versions such as std::function often avoid the
allocation for small objects by storing them inside the object, but
the standard does not require it. A moved-from Cell holds nothing,
so it may only be assigned to or destroyed.
Prefer a simpler tool when one fits:
- If you own every type and the set is fixed, a
std::variant<Money, Percent, Label>withstd::visitneeds no allocation and no virtual call. - If the types already share an interface you control, ordinary inheritance is clearer.
- If you only need one callable,
std::functionis type erasure already written for you.
Type erasure goes further: small-buffer storage, non-owning views, the strong guarantee for copying, and when a move-only wrapper fits.
Policy-based design: behaviour chosen at compile time
Section titled “Policy-based design: behaviour chosen at compile time”The problem
Section titled “The problem”The report can be written as CSV, which must quote fields that hold a comma, or as plain text separated by bars. The writer’s loop is the same; only the separator and the field escaping differ, and each program knows which format it wants when it is compiled.
The idiom
Section titled “The idiom”A policy is a small class that supplies one piece of behaviour, passed to a class template as a template parameter. A concept states what every policy must provide:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// What every row-format policy must provide, checked at compile time.// Read it as: Format::separator must exist and convert to a string_view,// and Format::field(text) must compile for a string_view text and give// something that converts to a std::string. Both are used through the// class name, with no object, so they must be static members.template <typename Format>concept RowFormat = requires(std::string_view text) { { Format::separator } -> std::convertible_to<std::string_view>; { Format::field(text) } -> std::convertible_to<std::string>;};
// A policy has no per-object data and no virtual functions: just a separator// fixed at compile time (static constexpr) and a static function.struct CsvFormat { static constexpr std::string_view separator = ","; // Quotes a field that holds a comma, a quote, or a line break, and // doubles any quotes inside it. static std::string field(std::string_view text);};
// Plain text needs no escaping: field returns the text unchanged.struct PlainFormat { static constexpr std::string_view separator = " | "; static std::string field(std::string_view text) { return std::string{text}; }};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Policy-based design: the format is a template parameter, chosen when the// code is compiled. RowWriter<CsvFormat> and RowWriter<PlainFormat> are// different types, and neither has a virtual call.// `template <RowFormat Format>` accepts only a type that meets the// RowFormat concept, so RowWriter<int> is rejected where it is written.template <RowFormat Format>class RowWriter {public: // Appends one row as one line: each cell's text, passed through the // policy's field, with the policy's separator between cells (not // before the first), then a newline. void add(const std::vector<Cell>& cells) { for (std::size_t i = 0; i < cells.size(); ++i) { if (i > 0) { text_ += Format::separator; } // Format::field is an ordinary call to a static function, fixed // when RowWriter<Format> is compiled; no virtual dispatch. text_ += Format::field(cells[i].text()); } text_ += '\n'; }
// Everything added so far: a reference to the writer's own string, so // nothing is copied. It must not be used after the writer is destroyed. const std::string& text() const { return text_; }
private: std::string text_;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The angle brackets pick the policy when the program is compiled:// two different types, built from the same RowWriter template.RowWriter<CsvFormat> csv;RowWriter<PlainFormat> plain;// `const std::vector<Cell>&` reads each row in place, without copying it.for (const std::vector<Cell>& row : rows) { csv.add(row); plain.add(row);}- The policies hold no per-object state and have no virtual
functions.
RowWriter<CsvFormat>callsCsvFormat::fielddirectly, with no virtual dispatch.PlainFormat::fieldis defined in the header, so the compiler can inline it;CsvFormat::fieldlives inrow_format.cpp, so only link-time optimization could inline it. - The concept checks the policy where it is named.
RowWriter<int>does not compile, and the error namesRowFormat, not a line deep insideadd. - Each choice is a different type.
RowWriter<CsvFormat>andRowWriter<PlainFormat>share no base class and cannot go in onestd::vector.
The standard library uses policies throughout: std::unique_ptr’s
deleter (the Close in TempFile is one), std::map’s comparison,
std::unordered_map’s hash, allocators, and std::char_traits for
std::basic_string. Classic policy-based design combines several
independent policies in one class template, such as a format, an
error-handling rule, and a locking rule; this example has one.
Resembles Strategy, chosen at compile time
Section titled “Resembles Strategy, chosen at compile time”A policy is a Strategy fixed when the code is compiled. The Strategy page shows both forms. Choose a policy when the choice is known at compile time and the call is frequent enough that a virtual call or the loss of inlining matters. Choose a run-time Strategy when the choice comes from configuration or user input, when several choices must be stored together, or when compile times and code size matter more: each policy instantiates the whole template again. Generic programming: templates, concepts, and policies goes further.
Running the example
Section titled “Running the example”csv:item,price,changekettle,24.99,+5%"lamp, desk",12.50,-10%plain:item | price | changekettle | 24.99 | +5%lamp, desk | 12.50 | -10%aligned:item price changekettle 24.99 +5%lamp, desk 12.50 -10%read back from a temporary file: the same textthe original keeps its value: 24.99, the copy now holds: +5%- The CSV policy quotes
"lamp, desk"because it holds a comma; the plain policy does not. - The aligned table pads the first column to its widest entry,
lamp, desk, and the second toprice, with two spaces between columns. - The temporary file reads back the CSV text exactly; the file is closed, and so removed, when the block ends.
- The copied cell holds a percentage after assignment, and the original still holds its price.
The tests check each idiom’s rules: formatting at the edges, deep copies and assignment between stored types, CSV quoting, row-size checks and moves for the table, and that the file reads back what was written:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// static_assert checks a condition while the program is compiled: if it is// false, the build fails. Here it proves the concepts accept and refuse the// right types, before any test runs.static_assert(CellValue<Money> && CellValue<Label>);static_assert(!CellValue<int>); // no to_text(int)static_assert(RowFormat<CsvFormat> && RowFormat<PlainFormat>);static_assert(!RowFormat<int>);
// LLD_TEST(name) defines one test. LLD_CHECK_EQ(actual, expected) records// a failure, printing both values, unless actual == expected.// LLD_CHECK_THROWS(expr, type) fails unless the expression throws that// type of exception. They come from the site's small test header,// lld_test.hpp.
// The edges of formatting: fewer than 10 cents needs a leading zero,// negative amounts get a "-", and INT_MIN (the most negative int,// -2147483648 cents where int is 32 bits, as the expected text assumes)// does not overflow when made positive. Percent shows "+" only above 0.LLD_TEST(values_format_as_text) { LLD_CHECK_EQ(to_text(Money{2499}), std::string{"24.99"}); LLD_CHECK_EQ(to_text(Money{5}), std::string{"0.05"}); LLD_CHECK_EQ(to_text(Money{-50}), std::string{"-0.50"}); LLD_CHECK_EQ(to_text(Money{INT_MIN}), std::string{"-21474836.48"}); LLD_CHECK_EQ(to_text(Percent{5}), std::string{"+5%"}); LLD_CHECK_EQ(to_text(Percent{0}), std::string{"0%"}); LLD_CHECK_EQ(to_text(Percent{-10}), std::string{"-10%"});}
// A Cell copies like a value: changing the copy never changes the original,// even when the copy is given a value of a different type.LLD_TEST(a_cell_is_a_value_that_copies_deeply) { Cell a = Label{"kettle"}; Cell b = a; // `b` gets its own Label, cloned from the one in `a` b = Money{100}; // `b` now holds a Money; `a` still holds its Label LLD_CHECK_EQ(a.text(), std::string{"kettle"}); LLD_CHECK_EQ(b.text(), std::string{"1.00"}); a = b; // copy assignment between different stored types LLD_CHECK_EQ(a.text(), std::string{"1.00"}); const Cell& same = a; a = same; // assigning a cell to itself keeps its value LLD_CHECK_EQ(a.text(), std::string{"1.00"}); Cell moved = std::move(a); // takes the pointer from `a`, which is now empty LLD_CHECK_EQ(moved.text(), std::string{"1.00"}); a = Percent{1}; // a moved-from cell can be assigned to again LLD_CHECK_EQ(a.text(), std::string{"+1%"});}
// CsvFormat::field adds quotes only around a field that holds a comma, a// quote, or a line break, and doubles each quote inside. In the literals,// \" stands for one quote character, so for the input `say "hi"` the// expected text is `"say ""hi"""`: inner quotes doubled, then the whole// field wrapped in quotes.LLD_TEST(the_csv_policy_quotes_only_when_needed) { LLD_CHECK_EQ(CsvFormat::field("plain"), std::string{"plain"}); LLD_CHECK_EQ(CsvFormat::field("a,b"), std::string{"\"a,b\""}); LLD_CHECK_EQ(CsvFormat::field("say \"hi\""), std::string{"\"say \"\"hi\"\"\""}); LLD_CHECK_EQ(CsvFormat::field("two\nlines"), std::string{"\"two\nlines\""}); LLD_CHECK_EQ(CsvFormat::field(""), std::string{});
const std::vector<Cell> row{Label{"lamp, desk"}, Money{1250}}; RowWriter<CsvFormat> csv; RowWriter<PlainFormat> plain; csv.add(row); plain.add(row); LLD_CHECK_EQ(csv.text(), std::string{"\"lamp, desk\",12.50\n"}); LLD_CHECK_EQ(plain.text(), std::string{"lamp, desk | 12.50\n"});}
// Column widths: column 0 is as wide as "cccc" (4) and column 1 as "bbb"// (3). Each entry except the last in a row is padded to its column's// width plus 2 spaces, so "a" is followed by (4 - 1) + 2 = 5 spaces and// "cccc" by (4 - 4) + 2 = 2. A one-column row and an empty row are both refused.LLD_TEST(the_table_aligns_columns_and_checks_row_sizes) { TableFormatter table; LLD_CHECK_EQ(table.render(), std::string{}); table.add_row({"a", "bbb"}); table.add_row({"cccc", "d"}); LLD_CHECK_EQ(table.render(), std::string{"a bbb\ncccc d\n"}); LLD_CHECK_THROWS(table.add_row({"only one"}), std::invalid_argument); LLD_CHECK_THROWS(table.add_row({}), std::invalid_argument);
TableFormatter moved = std::move(table); // the Impl moves; nothing is copied LLD_CHECK_EQ(moved.render(), std::string{"a bbb\ncccc d\n"});}
// The file starts empty, writing an empty string changes nothing, a write// after a read still appends at the end, and moving the TempFile moves the// one open file to the new object. The file is closed once, when the// moved-to object `moved` is destroyed at the end of the test.LLD_TEST(a_temp_file_reads_back_what_was_written) { TempFile file; LLD_CHECK_EQ(file.read_all(), std::string{}); file.write("one\n"); file.write(""); LLD_CHECK_EQ(file.read_all(), std::string{"one\n"}); file.write("two\n"); // after reading, writes still append LLD_CHECK_EQ(file.read_all(), std::string{"one\ntwo\n"});
TempFile moved = std::move(file); // the handle moves; the file stays open once LLD_CHECK_EQ(moved.read_all(), std::string{"one\ntwo\n"});}Summary table
Section titled “Summary table”| Idiom | Solves | Resembles | Costs | Simpler alternative |
|---|---|---|---|---|
| RAII | release on every path, including exceptions | no pattern | almost none; release errors are lost in destructors | none: use it for every resource |
| PImpl | private members in headers, recompiles, ABI breaks | Bridge, with one implementation | an allocation per object, an indirection per call | an ordinary class, or a header-only struct |
| Type erasure | unrelated types used as one value type | interface + Adapter + Prototype | usually an allocation and a virtual call | std::variant, inheritance, std::function |
| Policy-based design | behaviour fixed at compile time, without overhead | Strategy, chosen at compile time | one instantiation per policy; no run-time choice | a function parameter or a run-time Strategy |
Common mistakes
Section titled “Common mistakes”- A copyable RAII class with a raw handle. The compiler’s copy
constructor copies the handle, and both copies release it. Hold the
handle in a
std::unique_ptrwith a deleter, or delete the copies. - Throwing from a destructor. Destructors are
noexceptunless declarednoexcept(false), or a member or base destructor may throw, so an exception that leaves one ends the program. Report release errors from an explicit function instead. - Defaulting a PImpl destructor in the header. It fails to compile
where
Implis incomplete. Declare it in the header; default it in the.cppfile. - PImpl everywhere. It slows every object down to speed up builds; use it where the build or binary-interface problem is real.
- Type erasure for a closed set of types. If you own all the types,
std::variantis simpler and faster. - Calling a moved-from erased or PImpl object. Both hold a null pointer after a move.
- A policy for a choice made at run time. Then every use needs a
switchover the policies, which is a Strategy written the hard way.
When the requirements change
Section titled “When the requirements change”- Write errors must reach the caller: add
TempFile::close(), which flushes, closes, and throws on failure; the destructor still closes ifclosewas never called. TableFormattermust be copyable: write a copy constructor and copy assignment intable.cppthat make a newImplfrom*other.impl_.- Cells must be compared or sorted: add a function to
ConceptandModel, and to theCellValueconcept. Every stored type must then provide it, which is the price of a single interface. Comparing two different stored types needs a rule for mixed types; the simplest is to compare a common key, such as the text. - The format must come from a command-line flag: keep the policies
for the inner loop, and choose between
RowWriter<CsvFormat>andRowWriter<PlainFormat>once at the top, or switch to a run-time Strategy if the choice is made in many places.
Exercise: Match the idiom to the problem
For each problem, name the idiom that fits, or say that none is needed, and give one reason.
- A class wraps a POSIX file descriptor, an
intthat must be passed tocloseexactly once. - A widely used
Imageclass in a shared library adds a private cache member, and every program that uses the library has to be rebuilt. - A plug-in system stores callbacks of many different lambda types in one container and calls them all later.
- A hash table class lets its users choose the hash function. The choice is always known when the code is written, and lookups are in a hot loop.
- A UI library stores widgets of types written by its users, which
all derive from the library’s
Widgetbase class. - A geometry module has exactly three shape types, all written by the same team, and needs to compute their areas.
- A mutex must be unlocked on every path out of a function.
Show the explained answer
- RAII. A small class that owns the descriptor, closes it in its
destructor, and is move-only, so it can never be closed twice.
Mark the moved-from state with an invalid descriptor such as
-1. - PImpl. Moving the private members into an
Impldefined in the library’s.cppfiles lets the members change without changing the class’s size or layout, so programs need not be rebuilt for that kind of change. SwitchingImageto PImpl is itself one last ABI break; after that, private members can change freely. - Type erasure, already written:
std::function(or, from C++23,std::move_only_functionfor callables that cannot be copied). - Policy-based design, as the standard library does with
std::unordered_map’s hash parameter. The choice is known at compile time and the call is hot. - None needed. The types already share an interface the library
controls, so ordinary inheritance and
std::unique_ptr<Widget>are the clear choice. - None of the four. A closed set owned by one team fits
std::variantandstd::visit, or even three overloads ofarea. - RAII, already written:
std::lock_guardorstd::scoped_lock.
Summary
Section titled “Summary”- A pattern is a language-independent arrangement of collaborating roles; an idiom is a recurring way of writing something in one language. Idioms are smaller, and in C++ they are often how patterns are implemented.
- RAII releases a resource in a destructor, so it is released on
every path. Hold the resource in a member that already does this,
such as a
std::unique_ptrwith a deleter. - PImpl moves private members behind a pointer to an incomplete type, to shorten builds and keep a binary interface stable. It looks like Bridge but has one implementation and no variation.
- Type erasure lets unrelated types be used as one value type,
through a private interface and a generated adapter per type. Prefer
std::variantwhen you own a fixed set of types. - Policy-based design chooses behaviour through template parameters at compile time. It is Strategy without the run-time choice or the virtual call.