Null Object and Object Pool
What you will learn on this page
Section titled “What you will learn on this page”- What a Null Object is: an object that implements an interface by doing nothing, so that code which uses the interface needs no null checks.
- When a Null Object is correct, and when it hides a failure
that the caller needed to see, and why
std::optionalis the better answer then. - What an Object Pool is: a set of objects created once and lent out again and again, instead of being created and destroyed for each use.
- Why a pool is justified only when measurement shows that creating the objects costs enough to matter, and how to measure that.
- How to give a pool safe ownership in C++: a move-only lease that gives its object back when it ends, and the lifetime rules the pool and its leases must follow.
Neither pattern is in the original catalogue of 23. Both are common enough that you will meet them in code and in design discussions, and both are easy to use where they do not fit. The page treats them together because they share one question: is the problem this pattern solves really there?
Part 1: Null Object
Section titled “Part 1: Null Object”The problem
Section titled “The problem”An order importer reads lines such as ana,2000 (a customer id and an
amount in cents), looks up each customer, applies their discount, and
returns the orders. A line that does not parse, or that names an
unknown customer, is skipped. The importer can also say why it
skipped each line, which is useful in a command-line tool and noise in
a nightly batch job.
The customer directory and the result types:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One customer: a unique id (such as "ana"), a display name, and the// discount they get on every order. A plain struct of values: copying a// Customer copies all three fields.struct Customer { std::string id; std::string name; int discount_percent = 0; // 0 to 100
// `= default` asks the compiler to write ==: two customers are equal // when id, name, and discount are all equal. The tests rely on it. bool operator==(const Customer&) const = default;};
// Every known customer, looked up by id. It owns its customers by value// inside a map, so nothing here is borrowed.class CustomerDirectory {public: // Stores a customer. Takes the Customer by value and then moves it // into the map, so a caller passing a temporary pays for no copy of // the name; only the id is copied, to be the map's key. Throws // std::invalid_argument for an empty or repeated id, or a discount // outside 0 to 100. void add(Customer customer);
// A copy of the customer, or std::nullopt if there is no such id. // The optional return type puts "maybe missing" in the type itself, // so a caller cannot use the result as a Customer without checking. std::optional<Customer> find(std::string_view id) const;
private: // Sorted by id. std::less<> (with empty angle brackets) lets find // compare a std::string_view against the std::string keys directly, // without first building a std::string from the id. std::map<std::string, Customer, std::less<>> by_id_;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One accepted line: whose order it is and what they are charged.struct Order { std::string customer_id; int charged_cents = 0; // after the customer's discount, rounded down
bool operator==(const Order&) const = default;};
// What an import produced: the orders it accepted, in input order, and// how many lines it refused. The reasons for refusing go to the logger,// not here.struct ImportResult { std::vector<Order> orders; int skipped = 0;};
// Each line is "customer,amount_cents", with an amount from 1 to// 10000000 cents. A line that does not parse, or names an unknown// customer, is skipped, and the reason is logged; a summary is logged// at the end. Pass a NullLogger to discard the messages.// `Logger& log` is a reference: it cannot be null, so the function never// has to ask whether there is a logger. It borrows the logger only for// the length of the call. Never throws for a bad line; bad lines are// counted in `skipped`.ImportResult import_orders(const std::vector<std::string>& lines, const CustomerDirectory& customers, Logger& log);find returns std::optional<Customer>: “no such customer” is an
answer the importer must act on, by skipping the line. Keep that in
mind; it comes back in the section on hidden failures.
The straightforward solution: an optional pointer
Section titled “The straightforward solution: an optional pointer”The obvious way to make logging optional is a pointer that may be null:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Without a Null Object: the logger is optional, so every use checks it.// `Logger*` is a pointer that may hold nullptr, meaning "no logger". The// type alone does not say whether it is optional, borrowed, or owned;// the comment on the parameter has to.ImportResult import_orders(const std::vector<std::string>& lines, const CustomerDirectory& customers, Logger* log); // may be nullVerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The same import as the Null Object version (which takes Logger&), except// that `log` is a pointer that may be nullptr. parse_line, where, and// charge are small helpers earlier in this file: parse_line returns either// the parsed line or a std::string saying why it is bad, where(i) builds// "line 1: " and so on, and charge applies the discount.ImportResult import_orders(const std::vector<std::string>& lines, const CustomerDirectory& customers, Logger* log) { ImportResult result; for (std::size_t i = 0; i < lines.size(); ++i) { const std::variant<ParsedLine, std::string> parsed = parse_line(lines[i]); // std::get_if gives a pointer to the reason if the line was bad, // or nullptr if it parsed, so this branch handles bad lines only. if (const std::string* why = std::get_if<std::string>(&parsed)) { // Check 1 of 3. `log->log(...)` through a null pointer would be // undefined behaviour, so every call must be guarded like this. if (log != nullptr) { log->log(where(i) + *why); } ++result.skipped; continue; } const ParsedLine& line = std::get<ParsedLine>(parsed); const std::optional<Customer> customer = customers.find(line.customer_id); if (!customer) { if (log != nullptr) { // check 2 of 3: the same question again log->log(where(i) + "unknown customer \"" + std::string{line.customer_id} + "\""); } ++result.skipped; continue; } result.orders.push_back(Order{customer->id, charge(line.amount_cents, *customer)}); } if (log != nullptr) { // check 3 of 3, for the summary log->log("imported " + std::to_string(result.orders.size()) + ", skipped " + std::to_string(result.skipped)); } return result;}This works, and the example’s tests check that it gives the same orders as the version below. But look at what it costs:
- Three checks for one decision. The caller decided once whether it wants messages; the importer asks again at every place it logs.
- One missed check is a crash. A fourth
log->log(...)added later without the check is undefined behaviour when the caller passednullptr, and a test that always passes a logger never finds it. - The type says less.
Logger*could mean “optional”, “borrowed”, or “owned”; the comment has to say which.
The pattern
Section titled “The pattern”A Null Object is an object that implements the interface and does nothing. The caller who wants no messages passes one, and the code that logs never has to ask:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The interface: something that accepts one message at a time. Code that// logs depends only on this, never on which kind of logger it was given.class Logger {public: // Virtual, so deleting a logger through a Logger pointer (for // example from a std::unique_ptr<Logger>) runs the right destructor. virtual ~Logger() = default; // `= 0` makes it pure virtual: Logger has no log of its own, and each // concrete logger must supply one. string_view lets the caller pass // a string or a literal without making a copy. virtual void log(std::string_view message) = 0;
protected: // Protected, so only derived classes can construct or copy a Logger. // Code cannot assign one Logger& to another, which would copy only the // Logger part of two different loggers (slicing). Logger() = default; Logger(const Logger&) = default; Logger& operator=(const Logger&) = default;};
// The Null Object: a real Logger whose log does nothing. It has no data,// so every NullLogger behaves the same way. `final` means no class can// derive from it; there is nothing to extend. The parameter name is// commented out because the body never uses it, which keeps the compiler// from warning about an unused parameter.class NullLogger final : public Logger {public: void log(std::string_view /*message*/) override {} // empty body: discard the message};
// Keeps every message, for tests and for showing them later.class MemoryLogger final : public Logger {public: // Copies the message into a new std::string at the end of messages_: // the string_view only borrows the caller's text, so it must be copied // to be kept. void log(std::string_view message) override; const std::vector<std::string>& messages() const;
private: std::vector<std::string> messages_;};
// Writes each message on its own line, after a prefix.class StreamLogger final : public Logger {public: // Borrows out, which must outlive this logger. StreamLogger(std::ostream& out, std::string prefix); // Writes prefix_, then the message, then a newline, to out. void log(std::string_view message) override;
private: // A pointer rather than a reference member, so the class stays // assignable; the constructor takes a reference, so it is never null. std::ostream* out_; // never null std::string prefix_;};Text description of the diagram
A class diagram. Logger is an interface with one pure virtual function, log, which takes a string_view. Three classes implement it. NullLogger has no data members, and its log does nothing. MemoryLogger holds a vector of strings, and has log and a messages function that returns a constant reference to that vector. StreamLogger holds a pointer to an ostream, which it borrows, and a prefix string; its constructor takes an ostream reference and a prefix. The function import_orders takes a Logger reference and uses only the interface; it does not know which of the three it was given.
Diagram source (Mermaid)
classDiagram
class Logger {
<<interface>>
+log(string_view message)*
}
class NullLogger {
+log(string_view message)
}
class MemoryLogger {
-vector~string~ messages_
+log(string_view message)
+messages() const vector~string~&
}
class StreamLogger {
-ostream* out_
-string prefix_
+StreamLogger(ostream&, string prefix)
+log(string_view message)
}
class import_orders {
<<function>>
+import_orders(lines, customers, Logger&) ImportResult
}
Logger <|.. NullLogger
Logger <|.. MemoryLogger
Logger <|.. StreamLogger
StreamLogger --> ostream : out_ (borrowed)
import_orders ..> Logger : usesThe importer now takes Logger&. A reference cannot be null, so there
is nothing to check:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Reads the lines in order. Each line either becomes an Order or is// skipped with a logged reason; there is no third outcome. Three helpers// from earlier in this file do the small jobs: parse_line splits// "customer,amount_cents" and checks the amount, where(i) builds the// "line 2: " style prefix, and charge applies the discount, rounding down.ImportResult import_orders(const std::vector<std::string>& lines, const CustomerDirectory& customers, Logger& log) { ImportResult result; // An index loop rather than a range-for, because the messages need the // line number. where(i) adds 1, so the first line is "line 1". for (std::size_t i = 0; i < lines.size(); ++i) { // parse_line returns a std::variant: it holds either a ParsedLine // (the line was good) or a std::string (why it was bad), never both. const std::variant<ParsedLine, std::string> parsed = parse_line(lines[i]); // std::get_if returns a pointer to the string if the variant holds // one, and nullptr otherwise. Declaring `why` inside the if means // the branch runs only for a bad line, and `why` exists only there. if (const std::string* why = std::get_if<std::string>(&parsed)) { log.log(where(i) + *why); // no null check: log is a reference ++result.skipped; continue; // go straight to the next line } // Past the if, the variant must hold a ParsedLine, so std::get // cannot throw here. `const ParsedLine&` reads it in place. const ParsedLine& line = std::get<ParsedLine>(parsed); const std::optional<Customer> customer = customers.find(line.customer_id); // An empty optional converts to false: the id is not in the directory. if (!customer) { log.log(where(i) + "unknown customer \"" + std::string{line.customer_id} + "\""); ++result.skipped; continue; } // Only now is it safe to use `customer->` and `*customer`: the check // above proved the optional holds a Customer. result.orders.push_back(Order{customer->id, charge(line.amount_cents, *customer)}); } // One summary at the end, whether or not anything was skipped. log.log("imported " + std::to_string(result.orders.size()) + ", skipped " + std::to_string(result.skipped)); return result;}How this code works: import_orders
Each line goes through two gates. A line that fails either gate is
counted in skipped, its reason is logged, and continue moves on to
the next line. A line that passes both becomes an Order.
- Parse.
parse_linereturns astd::variantholding either aParsedLineor astd::stringwith the reason.std::get_ifasks “is it the string?”: it returns a pointer to the string, ornullptr. So the firstifruns only for a line that did not parse. - Look up. After the first
if, the variant must hold aParsedLine, sostd::getis safe.findreturns an emptystd::optionalfor an unknown id, and the secondifskips that line. - Charge. Only now does the code use
*customer.chargecomputesamount * (100 - discount) / 100; integer division rounds down. - Summary. After the loop, one last message reports both counts.
Notice that log.log(...) appears three times and is never guarded.
With NullLogger each call does nothing, and every other line runs
exactly as with StreamLogger.
With the five lines from main.cpp, where ana has 10 percent off
and raj none:
| Line | Text | What happens | Logged |
|---|---|---|---|
| 1 | ana,2000 |
parses; ana found; 2000 × 90 / 100 = 1800 |
nothing |
| 2 | bo,1500 |
parses; find("bo") is empty: skipped |
line 2: unknown customer "bo" |
| 3 | raj,12x |
12x is not a whole number: skipped |
line 3: bad amount "12x" |
| 4 | raj,999 |
parses; raj found; no discount, so 999 |
nothing |
| 5 | ana |
no comma: skipped | line 5: expected "customer,amount_cents" |
The result is two orders and three skipped lines, and the summary is
imported 2, skipped 3, as in the program’s output below.
The caller chooses once:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The caller decides once which logger to use. This one writes each// message to the console after " log: ". It borrows std::cout, which// lives for the whole program, so the borrow is safe.StreamLogger console{std::cout, " log: "};// console is passed as a Logger&: import_orders sees only the interface.const ImportResult result = import_orders(lines, customers, console);
// The same call with the Null Object: the import runs exactly as// before and every log call simply does nothing.NullLogger quiet; // for a caller that does not want the reasonsconst ImportResult again = import_orders(lines, customers, quiet);Reading the classes by role:
Loggeris the interface. Its destructor is virtual because a caller may own a logger through astd::unique_ptr<Logger>, which deletes it through the base. Its copy operations areprotected, so code cannot assign one logger to another through base references (a = bon twoLogger&), which would copy only theLoggerpart.NullLoggeris the Null Object. It has no data members and no state, so everyNullLoggerbehaves the same, and there is nothing to get wrong. It isfinalbecause there is nothing to extend.MemoryLoggerandStreamLoggerare ordinary implementations.MemoryLoggerowns its messages.StreamLoggerborrows the stream through a pointer that is never null; the stream must outlive it.
Why it fits here
Section titled “Why it fits here”A Null Object is correct when doing nothing is a complete and correct answer for every caller. For this logger, it is:
logreturns nothing, so the Null Object does not have to invent a result.- No caller depends on a message having been written. The orders are the same either way, and the example’s first test checks exactly that.
- “Discard the messages” is a real choice a caller makes on purpose, not a mistake.
When all three hold, the Null Object removes the checks without removing any information.
When a Null Object hides a failure
Section titled “When a Null Object hides a failure”The same idea applied to the customer lookup goes wrong. Suppose
someone wants to remove the if (!customer) check from the importer
too, and returns a “null customer” for an unknown id:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A Null Object where "nothing" is a real answer: an unknown id returns// a customer named "(unknown)" with no discount, and nothing says so.// The flaw is in the return type: it is a plain Customer, not an// optional, so the caller cannot tell a real customer from the invented// one (whose id is the empty string) without comparing fields by hand.Customer find_or_unknown(const CustomerDirectory& customers, std::string_view id);VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The flaw: find_or_unknown always returns a Customer, so there is// nothing to check. For an unknown id such as "bo" it returns the// made-up customer with id "" and 0 percent discount, and the line// below records an order for that empty id at the full amount. No// message is logged and `skipped` is not incremented.const Customer customer = find_or_unknown(customers, line.customer_id);result.orders.push_back(Order{customer.id, charge(line.amount_cents, customer)}); // never skippedThe difference from the logger is the first two conditions above:
find returns a value, so a Null Object must invent one, and the
caller depends on knowing whether the customer exists. For a lookup,
“there is no such customer” is information the caller must act
on: skip the line, ask the user, or stop. A Null Object answers
for the caller, with a made-up name and a made-up discount, and every
later step treats the made-up answer as real.
Use std::optional (or an error) whenever the absence changes what
the caller should do. find already returns std::optional<Customer>:
the type tells the caller the value may be missing, and the caller
cannot use it as a Customer without unwrapping it. Unwrapping with
* or -> when it is empty is undefined behaviour, so test it with
if (customer), as the importer does, or use value(), which throws.
| You have | Use | Why |
|---|---|---|
| An action whose “do nothing” form is correct for every caller | A Null Object | Removes the checks and loses no information |
| A query that may have no answer, and the caller must decide | std::optional<T> |
The caller has to unwrap it, which makes the absence visible |
| An operation that can fail for a reason the caller needs | An exception, or a result type that carries the reason | “Absent” alone does not say what went wrong |
| A borrowed object that may legitimately be missing, rarely checked | A pointer that may be null, with a comment saying so (std::optional cannot hold a reference) |
Honest when the checks really are rare |
Warning signs
Section titled “Warning signs”You are probably hiding a failure when the Null Object:
- Returns a value that it had to invent: a price of 0, an empty name, a “guest” user, a default exchange rate. Each invented value is a guess about what every caller wants.
- Is compared against. Code such as
if (customer.name == "(unknown)")is a null check written the long way. - Appears in production for something that must be configured. A
NullPaymentGatewaythat silently “succeeds” turns a missing setting into lost money. In a test, the same class can be fine, because there the test chose it on purpose.
Testing it
Section titled “Testing it”The tests check the one thing that makes this Null Object correct: it
changes nothing except whether the messages are kept. They also check
that the null-check version agrees, and that find says when a
customer is missing:
VerifiedCompiled 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) does the same// for actual == expected and prints both values when they differ, so it// is used for values that can be printed (numbers, strings). Vectors// cannot be printed, so they are compared with LLD_CHECK, and the extra// parentheses in LLD_CHECK((...)) keep any comma inside the expression// from being read as a second macro argument. LLD_CHECK_THROWS(expr,// type) fails unless the expression throws that type of exception. All// four come from the site's small test header, lld_test.hpp.// two_customers() is a helper above that returns a directory holding// "ana" (10 percent off) and "raj" (no discount).
// The heart of the Null Object's correctness: the same input gives the// same orders and the same count of skipped lines whether the messages// are kept (MemoryLogger) or thrown away (NullLogger).// The seven lines: two good ones, then an unknown id ("bo"), an amount// with a stray letter ("12x"), a line with no comma ("ana"), a line with// no customer before the comma (",5"), and an amount of 0 ("raj,0").LLD_TEST(the_null_logger_changes_nothing_but_the_messages) { const CustomerDirectory customers = two_customers(); const std::vector<std::string> lines{"ana,2000", "bo,1500", "raj,12x", "raj,999", "ana", ",5", "raj,0"}; MemoryLogger kept; NullLogger quiet; const ImportResult logged = import_orders(lines, customers, kept); const ImportResult unlogged = import_orders(lines, customers, quiet); LLD_CHECK((logged.orders == unlogged.orders)); LLD_CHECK_EQ(logged.skipped, unlogged.skipped); // ana's 2000 less 10 percent is 1800; raj has no discount, so 999 stays 999. LLD_CHECK((logged.orders == std::vector<Order>{{"ana", 1800}, {"raj", 999}})); LLD_CHECK_EQ(logged.skipped, 5); LLD_CHECK_EQ(kept.messages().size(), std::size_t{6}); // five reasons and a summary LLD_CHECK_EQ(kept.messages().back(), std::string{"imported 2, skipped 5"});}
// The pointer version (namespace before) must agree with the Null Object// version, both when it is given a logger and when it is given nullptr.// "raj,10000001" is one cent over the 10'000'000 limit and is refused;// "raj,10000000" is exactly at the limit and is accepted.LLD_TEST(the_null_check_version_gives_the_same_result) { const CustomerDirectory customers = two_customers(); const std::vector<std::string> lines{"ana,2000", "bo,1500", "raj,10000001", "raj,10000000"}; MemoryLogger a; MemoryLogger b; const ImportResult with_object = import_orders(lines, customers, a); const ImportResult with_pointer = before::import_orders(lines, customers, &b); const ImportResult with_null = before::import_orders(lines, customers, nullptr); LLD_CHECK((with_object.orders == with_pointer.orders)); LLD_CHECK((with_object.orders == with_null.orders)); LLD_CHECK((a.messages() == b.messages())); // messages()[0] is line 2's unknown customer; [1] is line 3's amount. LLD_CHECK_EQ(a.messages()[1], std::string{"line 3: bad amount \"10000001\""});}
// A StreamLogger can write to any std::ostream. A std::ostringstream// collects the output in memory, so the test can read it back with str().LLD_TEST(a_stream_logger_writes_one_line_per_message) { std::ostringstream out; StreamLogger logger{out, "> "}; logger.log("one"); logger.log("two"); LLD_CHECK_EQ(out.str(), std::string{"> one\n> two\n"});}
// The lookup reports absence honestly, and add refuses bad customers.LLD_TEST(find_returns_nothing_for_an_unknown_id) { const CustomerDirectory customers = two_customers(); // Comparing an optional with a Customer is true only if the optional // holds a Customer equal to it. LLD_CHECK((customers.find("ana") == Customer{"ana", "Ana", 10})); LLD_CHECK(!customers.find("bo")); // an empty optional: no such customer CustomerDirectory more; LLD_CHECK_THROWS(more.add({"", "No id", 0}), std::invalid_argument); LLD_CHECK_THROWS(more.add({"x", "X", 101}), std::invalid_argument); more.add({"x", "X", 0}); // a valid customer, so the next add repeats its id LLD_CHECK_THROWS(more.add({"x", "Again", 0}), std::invalid_argument);}The flawed version has its own test, which records what goes wrong rather than what should happen:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// This test records what the flawed design does, not what it should do.// It passes, and that is the problem: each check below confirms a way// the null customer hides the unknown id "bo". (LLD_TEST, LLD_CHECK, and// LLD_CHECK_EQ are the test macros from lld_test.hpp; two_customers()// returns a directory with "ana" and "raj" only.)LLD_TEST(a_null_customer_hides_the_unknown_id) { const CustomerDirectory customers = two_customers(); // Looks like a customer with no discount; nothing says the id was wrong. LLD_CHECK_EQ(flawed::find_or_unknown(customers, "bo").name, std::string{"(unknown)"});
MemoryLogger log; const ImportResult result = flawed::import_orders({"ana,2000", "bo,1500"}, customers, log); LLD_CHECK_EQ(result.skipped, 0); // "bo,1500" was not refused LLD_CHECK((result.orders.back() == Order{"", 1500})); // an order for nobody, at full price LLD_CHECK_EQ(log.messages().size(), std::size_t{1}); // only the summary}Running the Null Object example
Section titled “Running the Null Object example” log: line 2: unknown customer "bo" log: line 3: bad amount "12x" log: line 5: expected "customer,amount_cents" log: imported 2, skipped 3quiet import: 2 imported, 3 skippedsame orders both times: yesthe null-check version agrees: yes (4 messages kept)with a null customer: 3 imported, 2 skipped an order for no customer, charged 1500 cents- The first four lines are the console logger’s messages: three reasons and a summary.
- The
NullLoggerimport prints nothing and gives the same orders. - The null-check version agrees, and with a
MemoryLoggerit kept the same four messages. - The last two lines are the flawed importer: three orders, one of them for no customer, at full price.
Simpler forms of the same idea
Section titled “Simpler forms of the same idea”You do not always need a class. If the interface is a single function,
a std::function<void(std::string_view)> parameter whose default is
a lambda that does nothing is the same idea with less code. If most
callers want no messages, an overload of import_orders without the
logger parameter can create a local NullLogger and call the full
version, so only the callers who care mention logging at all.
Part 2: Object Pool
Section titled “Part 2: Object Pool”The problem
Section titled “The problem”Some objects are expensive to create: a large buffer, a database connection that needs a network handshake, a thread, a GPU texture. A program that creates one, uses it briefly, and destroys it, many times a second, may spend a noticeable part of its time on creation and destruction rather than on the work.
An Object Pool creates a fixed set of these objects once, lends one out when asked, and takes it back when the borrower is finished, so the next borrower reuses it.
Two warnings come before any code:
- Ordinary allocation in C++ is often not the bottleneck. The general-purpose allocator is designed for frequent small allocations. Do not assume a program needs a pool because it allocates a lot; measure it.
- Most reuse needs no pool at all. The simplest form keeps one object alive across a loop:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The simplest reuse needs no pool: one string, kept outside the loop.// clear() empties it; the major standard libraries keep its capacity, so// later lines reuse the memory.std::string line;// The loop runs over a brace list of two names; each is a string_view,// a cheap view of the literal text.for (const std::string_view name : {"ana", "raj"}) { line.clear(); // empty the text, keep the memory line += "hello, "; line += name; std::cout << line << '\n';}std::string::clear() empties the string. The standard does not
promise that it keeps the capacity, but the major standard libraries
do, so later iterations reuse the memory. (These two short lines fit
in the string’s small built-in buffer anyway; the reuse matters for
longer lines.) std::vector::clear() does keep its capacity, and
reserve sets it up front. Reach for a pool only when the objects
must be handed out to different owners and come back.
The pattern
Section titled “The pattern”The example pool holds equal-sized byte buffers, for a program that fills a buffer with a message, sends it, and then needs the buffer again:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A fixed set of equal-sized buffers, lent out one at a time.// Not thread-safe: use it from one thread, or guard it with a mutex.// The pool owns every buffer for its whole life; borrowers get a Lease,// which has the use of one buffer until the Lease ends.class BufferPool {public: // Declared here and defined below the pool, so the two classes can // refer to each other: try_acquire returns a Lease, and a Lease calls // back into the pool. class Lease;
// Allocates `count` buffers of `size` bytes each, once, all zeroed. // Throws std::invalid_argument if either is 0. BufferPool(std::size_t count, std::size_t size); // No copying, and (because copying is deleted) no moving either: each // lease holds the pool's address, so the pool must never be copied or // moved to another address. BufferPool(const BufferPool&) = delete; // leases point at the pool BufferPool& operator=(const BufferPool&) = delete; ~BufferPool(); // every lease must have ended (checked by assert)
// A lease on a free buffer, or std::nullopt if every buffer is lent out. // An empty pool is a normal answer the caller must handle, which is why // the result is an optional and not a "null buffer". Never allocates. std::optional<Lease> try_acquire();
std::size_t available() const; std::size_t buffer_size() const;
private: // Wipes the buffer and marks it free again. Private, yet Lease can call // it: a nested class may use the private members of the class around // it. noexcept, because it runs from Lease's destructor. void give_back(std::size_t index) noexcept;
// Each buffer is a std::vector<char> of buffer_size() bytes. Buffers // are named by their index in this vector. std::vector<std::vector<char>> buffers_; // never resized after construction // Used as a stack: the last index pushed is the next one lent out. std::vector<std::size_t> free_; // indices of free buffers; room reserved for all};
// The one owner of a lent buffer. Move-only; when it ends, it wipes the// buffer and gives it back. This is RAII: the buffer is returned by the// destructor, so it comes back even on an early return or an exception.// A lease does not own memory; it holds the pool's address and the index// of its buffer.class BufferPool::Lease {public: // Moving hands the buffer to the new lease; the old one holds nothing. Lease(Lease&& other) noexcept; Lease& operator=(Lease&& other) noexcept; // gives back its own buffer first // No copies: two leases on one buffer would both give it back. Lease(const Lease&) = delete; Lease& operator=(const Lease&) = delete; ~Lease();
// buffer_size() bytes; empty after this lease has been moved from. // A std::span is a view (a pointer and a length) of the buffer's bytes: // it borrows them, so it is valid only while this lease holds the buffer. std::span<char> bytes() const;
private: // The constructor is private, and only BufferPool is a friend, so only // the pool can create a lease, and only for a buffer it took off free_. friend class BufferPool; Lease(BufferPool& pool, std::size_t index); // Gives the buffer back if this lease still holds one; safe to call twice. void release() noexcept;
BufferPool* pool_; // null after a move std::size_t index_;};Text description of the diagram
A class diagram with two classes and the buffers they manage. BufferPool holds a vector of buffers, each a vector of char, and a vector of the indices of the free buffers. Its public functions are a constructor taking a count and a size, try_acquire, which returns an optional Lease, available, and buffer_size; give_back, which takes an index, is private. Lease holds a pointer to the pool and the index of its buffer. It has a move constructor and a move assignment, and bytes, which returns a span of char; release is private. A filled-diamond line shows that the pool owns one or more buffers. A plain arrow shows that a Lease borrows the pool, and a dashed arrow shows that it uses one buffer, chosen by its index.
Diagram source (Mermaid)
classDiagram
class BufferPool {
-vector~vector~char~~ buffers_
-vector~size_t~ free_
+BufferPool(size_t count, size_t size)
+try_acquire() optional~Lease~
+available() const size_t
+buffer_size() const size_t
-give_back(size_t index)
}
class Lease {
-BufferPool* pool_
-size_t index_
+Lease(Lease&&)
+operator=(Lease&&) Lease&
+bytes() const span~char~
-release()
}
class buffer {
<<vector of char>>
}
BufferPool *-- "1..*" buffer : buffers_ (owns)
Lease --> BufferPool : pool_ (borrows)
Lease ..> buffer : uses one, by index_class BufferPool
owns every buffer; not copyable or movable: leases point at it
Data members
std::vector<std::vector<char>> buffers_;owned; never resized after constructionstd::vector<std::size_t> free_;indices of free buffers; capacity reserved for all
Member functions
BufferPool(std::size_t count, std::size_t size);allocates once; throws std::invalid_argument for 0~BufferPool();every lease must have endedstd::optional<Lease> try_acquire();std::nullopt when all are lent outstd::size_t available() const;std::size_t buffer_size() const;void give_back(std::size_t index) noexcept;private: wipes the buffer and records it as free; never allocates
class BufferPool::Lease
the one owner of a lent buffer: move-only RAII handle
Data members
BufferPool* pool_;borrowed; null after a movestd::size_t index_;which buffer
Member functions
Lease(Lease&& other) noexcept;other no longer holds the bufferLease& operator=(Lease&& other) noexcept;gives back its own buffer first~Lease();wipes the buffer and gives it backstd::span<char> bytes() const;valid while this lease holds the buffervoid release() noexcept;private: gives the buffer back once; does nothing after a move
The C++ implementation
Section titled “The C++ implementation”The pool allocates every buffer in its constructor and never again. Giving a buffer back wipes it and records its index as free:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Does all the allocating the pool will ever do, up front. Refuses a pool// of no buffers or of empty buffers by throwing std::invalid_argument.BufferPool::BufferPool(std::size_t count, std::size_t size) { if (count == 0 || size == 0) { throw std::invalid_argument{"BufferPool: count and size must be at least 1"}; } buffers_.reserve(count); free_.reserve(count); // so give_back never allocates for (std::size_t i = 0; i < count; ++i) { // emplace_back(size, '\0') builds a std::vector<char> of `size` // zero bytes directly inside buffers_. buffers_.emplace_back(size, '\0'); // Indices go in backwards: for count 3, free_ becomes 2, 1, 0. The // back of the vector is the top of the stack, so 0 is lent first. free_.push_back(count - 1 - i); // buffer 0 is lent first }}
// assert stops the program with a message if the condition is false, but// only in a debug build; with NDEBUG defined (a typical release build) it// checks nothing. All buffers back in free_ means no lease is still alive.BufferPool::~BufferPool() { assert(free_.size() == buffers_.size() && "a lease outlived its pool"); }
// Takes the top index off the free stack and wraps it in a Lease.std::optional<BufferPool::Lease> BufferPool::try_acquire() { if (free_.empty()) { return std::nullopt; // every buffer is lent out: an empty optional } const std::size_t index = free_.back(); // read the top of the stack free_.pop_back(); // then remove it: no longer free // The pool may call Lease's private constructor because it is a friend. // The new Lease is moved into the returned optional. return Lease{*this, index};}
// The other half of the stack: push the index back, after wiping.void BufferPool::give_back(std::size_t index) noexcept { std::vector<char>& buffer = buffers_[index]; std::fill(buffer.begin(), buffer.end(), '\0'); // the next user sees no old data free_.push_back(index); // cannot allocate: room was reserved}The details that matter:
try_acquirereturnsstd::optional<Lease>. An empty pool is a normal situation the caller must handle: wait, drop the message, or create a buffer outside the pool. This is Part 1’s rule again: the pool does not hand out a “null buffer”, because “there is none” is information the caller needs.free_reserves room for every index in the constructor, sogive_backnever allocates and cannot throw. That is what makesnoexcepton it honest, and it matters becausegive_backruns from a destructor.- The buffer is wiped on return. Without that, the next borrower could read the previous one’s data: a bug at best and a leak of private data at worst. Wiping costs one pass over the buffer per return; a pool of buffers that hold nothing sensitive could skip it, but then every borrower must overwrite before reading.
- The free list is a stack. The buffer given back last is lent first, so a buffer that was just used, and may still be in the CPU cache, is reused.
The lease is a move-only handle that gives the buffer back when it ends:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Stores where to give the buffer back (the pool's address) and which// buffer it is. Private: only BufferPool::try_acquire calls it.BufferPool::Lease::Lease(BufferPool& pool, std::size_t index) : pool_{&pool}, index_{index} {}
// std::exchange(other.pool_, nullptr) does two things at once: it returns// other's pool pointer (which this lease takes) and sets other's pointer// to nullptr. A lease with a null pool_ holds nothing, so other's// destructor will give nothing back. index_ is just copied; without a// pool it is never used.BufferPool::Lease::Lease(Lease&& other) noexcept : pool_{std::exchange(other.pool_, nullptr)}, index_{other.index_} {}
// `a = std::move(b)`: `a` gives back the buffer it holds (if any), then// takes the buffer of `b`, and `b` is left holding nothing.BufferPool::Lease& BufferPool::Lease::operator=(Lease&& other) noexcept { // Moving a lease into itself must change nothing; without this check, // release() would give the buffer back and the lease would then copy // its own, now null, pointer and end up empty. if (this != &other) { release(); // return the old buffer first, or the pool loses it pool_ = std::exchange(other.pool_, nullptr); index_ = other.index_; } return *this;}
// The RAII step: whenever a lease ends (end of scope, reset(), erase from// a container), its buffer goes back.BufferPool::Lease::~Lease() { release(); }
// Shared by the destructor and move assignment. The null check makes it// safe on a moved-from lease, and setting pool_ to null afterwards makes// a second call do nothing, so a buffer is never given back twice.void BufferPool::Lease::release() noexcept { if (pool_ != nullptr) { pool_->give_back(index_); pool_ = nullptr; }}
std::span<char> BufferPool::Lease::bytes() const { if (pool_ == nullptr) { return {}; // a moved-from lease: an empty span, not a null pointer read } // A std::vector<char> converts to a std::span<char> covering all of it. return pool_->buffers_[index_];}How this code works: BufferPool::Lease
A lease is either holding a buffer (pool_ points at the pool) or
empty (pool_ is nullptr). Every function keeps to that one rule.
- Created by the pool.
try_acquirepops an index offfree_and calls the private constructor, which stores the pool’s address and the index. The lease is now holding. - Move construction, as in
Lease moved = std::move(lease).std::exchange(other.pool_, nullptr)hands the pool pointer to the new lease and leavesnullptrbehind in one step. Now only the new lease is holding; the old one is empty. - Move assignment, as in
a = std::move(b), whenais already holding a buffer. Firsta.release()givesa’s own buffer back. Thenatakesb’s pointer and index, andbis left empty. If the first step were missing,a’s old buffer would never return tofree_, and the pool would have one buffer fewer for the rest of its life. - The end. The destructor calls
release. For a holding lease, that callsgive_back, which wipes the bytes and pushes the index ontofree_, then setspool_tonullptr. For an empty lease it does nothing. bytes. A holding lease returns a span over its buffer; an empty one returns an empty span, so a caller who uses a moved-from lease gets zero bytes rather than a crash.
- Only the pool can create a lease. The constructor is private and
BufferPoolis a friend, so no code can make a lease for a buffer it was not given. - Moving transfers the one owner.
std::exchangeleaves the moved-from lease with a null pool pointer, so its destructor does nothing, andbyteson it returns an empty span instead of reading through a null pointer. - Move assignment gives back its own buffer first. Otherwise the
lease it held would be lost, and the pool would shrink by one each
time. The
this != &othercheck stops a lease moved into itself from giving its buffer back and ending up empty. - No copies. Two leases on one buffer would give it back twice:
its index would be in the free list twice, so two later borrowers
would get the same buffer, and the second
give_backwould go past the reserved room and allocate inside anoexceptfunction.
Ownership and lifetime
Section titled “Ownership and lifetime”- The pool owns every buffer for its whole life. A lease never owns memory; it has exclusive use of one buffer until it ends.
- The pool must outlive every lease. A lease holds a pointer to
its pool, and its destructor calls
give_backthrough it. The pool’s destructor checks that every buffer is back withassert, which catches the mistake in debug builds only. In a release build, a lease that outlives its pool is undefined behaviour. - The pool cannot be copied or moved. Leases point at it, so it must stay where it is. Deleting the copy operations also stops the compiler from generating move operations, which is what we want here.
- A span from
bytesis a borrow of a borrow. It is valid only while the lease that returned it still holds the buffer: not after the lease ends, and not after it is moved from. - The pool is not thread-safe. Two threads calling
try_acquireat once would race onfree_. Use it from one thread, give each thread its own pool, or guard it with a mutex, and measure again, because a contended lock can cost more than the allocation it replaced.
Running the Object Pool example
Section titled “Running the Object Pool example”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
BufferPool pool{2, 32}; // two buffers of 32 bytes, allocated now and only now// Remembers where the first buffer lives, to show later that the same// memory is lent again. Only the address is kept, never read through.const char* first_address = nullptr;{ // an inner block, so the leases end at its closing brace std::optional<BufferPool::Lease> first = pool.try_acquire(); // buffer 0 std::optional<BufferPool::Lease> second = pool.try_acquire(); // buffer 1 // Both buffers are lent out, so this optional is empty. const std::optional<BufferPool::Lease> third = pool.try_acquire(); // An optional converts to true only if it holds a lease. std::cout << "lent out " << 2 - pool.available() << " of 2; a third request gets: " << (third ? "a buffer" : "nothing") << '\n';
// first-> reaches the Lease inside the optional. That is safe only // because first is known to hold one; on an empty optional it would // be undefined behaviour. write_message copies "hello" into the // buffer's bytes and returns 5, the number of bytes written. const std::size_t length = write_message(first->bytes(), "hello"); // A string_view of just the first `length` bytes of the buffer. std::cout << "first buffer holds: " << std::string_view{first->bytes().data(), length} << '\n'; first_address = first->bytes().data();} // the leases end here, in reverse order, and give their buffers backstd::cout << "after the leases end, available: " << pool.available() << '\n';
// Buffer 0 was given back last, so it is on top of the free stack and is// lent again; give_back has already wiped it.const std::optional<BufferPool::Lease> again = pool.try_acquire();hello, anahello, rajlent out 2 of 2; a third request gets: nothingfirst buffer holds: helloafter the leases end, available: 2the next lease reuses the same buffer: yesand it was wiped: yes- The first two lines come from the string-reuse loop.
- The pool lends both of its buffers, and a third request gets
std::nullopt. - When the block ends, the leases’ destructors give both buffers back.
- The next lease gets the buffer that was lent first, and it has been wiped. The leases end in reverse order, so the first lease gives its buffer back last, and the stack of free buffers lends it first.
The tests check the same rules, including that a moved-from lease gives nothing back and that move assignment returns the buffer it held:
VerifiedCompiled 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) does the same// for ==, and prints both values when they differ; 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.
// Lending and refusing: two buffers can be lent, a third request gets an// empty optional, and ending a lease makes its buffer available again.LLD_TEST(a_pool_lends_each_buffer_once_and_refuses_when_empty) { BufferPool pool{2, 8}; LLD_CHECK_EQ(pool.available(), std::size_t{2}); LLD_CHECK_EQ(pool.buffer_size(), std::size_t{8}); std::optional<BufferPool::Lease> a = pool.try_acquire(); std::optional<BufferPool::Lease> b = pool.try_acquire(); LLD_CHECK(a && b); // both optionals hold a lease LLD_CHECK(a->bytes().data() != b->bytes().data()); // two different buffers LLD_CHECK_EQ(a->bytes().size(), std::size_t{8}); LLD_CHECK(!pool.try_acquire()); // none left: an empty optional // reset() destroys the Lease inside the optional, so its destructor runs. a.reset(); // the lease ends, and the buffer goes back LLD_CHECK_EQ(pool.available(), std::size_t{1}); // The returned optional is a temporary, destroyed at the end of this // statement, so the lease it holds gives the buffer straight back. LLD_CHECK(pool.try_acquire().has_value()); // a temporary lease: back at once LLD_CHECK_EQ(pool.available(), std::size_t{1});
// A pool of no buffers, or of zero-byte buffers, is refused. LLD_CHECK_THROWS(BufferPool(0, 8), std::invalid_argument); LLD_CHECK_THROWS(BufferPool(2, 0), std::invalid_argument);}
// One buffer of 4 bytes: fill it, end the lease, and lease it again. The// second lease must get the same memory, now all zero bytes.LLD_TEST(a_returned_buffer_is_wiped_and_reused) { BufferPool pool{1, 4}; const char* address = nullptr; { // the lease ends at the closing brace const std::optional<BufferPool::Lease> lease = pool.try_acquire(); write_message(lease->bytes(), "abcd"); address = lease->bytes().data(); } const std::optional<BufferPool::Lease> again = pool.try_acquire(); LLD_CHECK(again->bytes().data() == address); // the same buffer, reused // std::all_of asks the lambda about every byte; true only if all are zero. LLD_CHECK(std::all_of(again->bytes().begin(), again->bytes().end(), [](char c) { return c == '\0'; })); // Five characters do not fit in four bytes, so write_message refuses. LLD_CHECK_THROWS(write_message(again->bytes(), "abcde"), std::length_error);}
// Moving a lease hands over the one buffer it holds; at no point do two// leases hold the same buffer, and no buffer is lost or given back twice.LLD_TEST(moving_a_lease_moves_the_one_owner) { BufferPool pool{2, 4}; std::optional<BufferPool::Lease> first = pool.try_acquire(); // *first is the Lease inside the optional. std::move lets the move // constructor take its buffer. The optional still holds a Lease // object, but that lease is now empty. BufferPool::Lease moved = std::move(*first); LLD_CHECK(first->bytes().empty()); // moved from: holds nothing first.reset(); // and gives nothing back LLD_CHECK_EQ(pool.available(), std::size_t{1}); // moved still holds one
std::optional<BufferPool::Lease> second = pool.try_acquire(); LLD_CHECK_EQ(pool.available(), std::size_t{0}); moved = std::move(*second); // moved gives back its own buffer first LLD_CHECK_EQ(pool.available(), std::size_t{1});
std::vector<BufferPool::Lease> kept; // move-only leases can live in containers kept.push_back(std::move(moved)); // the vector's lease now holds the buffer kept.clear(); // destroys that lease: its buffer goes back second.reset(); // second was moved from, so it gives nothing back LLD_CHECK_EQ(pool.available(), std::size_t{2}); // both back, each exactly once}How this code works: moving_a_lease_moves_the_one_owner
The pool has two buffers, 0 and 1. The constructor pushes the indices
in reverse, so free_ starts as [1, 0], and the back of the vector,
0, is lent first.
| Step | first |
moved |
second |
kept[0] |
free_ |
available() |
|---|---|---|---|---|---|---|
| start | none | none | none | none | [1, 0] |
2 |
first = pool.try_acquire() |
0 | none | none | none | [1] |
1 |
moved = std::move(*first) |
empty | 0 | none | none | [1] |
1 |
first.reset() |
none | 0 | none | none | [1] |
1 |
second = pool.try_acquire() |
none | 0 | 1 | none | [] |
0 |
moved = std::move(*second) |
none | 1 | empty | none | [0] |
1 |
kept.push_back(std::move(moved)) |
none | empty | empty | 1 | [0] |
1 |
kept.clear() |
none | empty | empty | none | [0, 1] |
2 |
second.reset() |
none | empty | none | none | [0, 1] |
2 |
“Empty” is a lease that has been moved from; “none” is an optional or
vector slot with no lease in it. Two rows carry the test’s point. At
first.reset(), the moved-from lease gives nothing back, so
available() stays 1. At moved = std::move(*second), moved
returns buffer 0 before it takes buffer 1, so available() goes from 0
to 1. At the end both buffers are back, each exactly once.
Is a pool justified? Measure first
Section titled “Is a pool justified? Measure first”This page reports no timings, because a timing from one machine and one workload says little about yours. What it can give you is a way to find out:
- Measure the real program first, built with optimisation on
(for example
-O2), on realistic input. A debug build or a two-line test tells you nothing about allocation cost. - Find where the time goes with a profiler, such as
perfon Linux. A pool is worth considering only if creating and destroying these objects, includingmalloc,free, and the constructor’s own work, is a large share of the time. - Count allocations with a heap profiler (for example
heaptrack, or Valgrind’smassiffor memory use). Many allocations per request is a hint; it is not proof of a cost. - Try the cheaper fixes first: reuse one object across a loop,
reservethe containers, or pass a buffer in from the caller. - Build the pool, then measure again with the same input, several runs each. Keep it only if the difference is clear and matters for the program’s goals, such as throughput or the slowest requests.
If the object is expensive for a reason other than memory, such as a network handshake or starting a thread, the cost is usually easy to see and the case for a pool is stronger. Connection pools and thread pools are common for that reason.
What a pool costs
Section titled “What a pool costs”- Memory held forever. The pool keeps every buffer allocated even when the program is idle.
- A fixed shape. Every buffer here has one size. Messages that are sometimes 10 bytes and sometimes 10 MB do not fit one pool.
- A new failure mode. An empty pool is a situation the caller must
handle, which a plain
std::vector<char>never had. - Lifetime rules. The pool must outlive every lease, and spans must not outlive their lease, which plain values do not need.
- Weaker tools. AddressSanitizer reports use of memory after it is freed, but a pooled buffer is never freed: code that keeps using a buffer after its lease ends reads valid memory that now belongs to someone else, and the sanitizer has nothing to report, unless the pool marks returned buffers as off-limits with AddressSanitizer’s manual poisoning interface. Wiping on return makes such a bug more likely to show up, but does not guarantee it.
When to use them
Section titled “When to use them”Null Object
- An interface whose operations are actions (log, notify, record a metric) and where “do nothing” is correct for every caller.
- To remove repeated null checks for a dependency that is optional by design.
- In tests, as a stand-in for a dependency the test does not care about.
Object Pool
- Objects that are expensive to create compared with the work done with them, created and destroyed often, where measurement confirms the cost.
- A fixed limit is useful in itself: at most 20 database connections, at most 8 buffers in flight. A pool enforces the limit as well as saving work.
When not to use them
Section titled “When not to use them”Null Object
- When absence is information: a lookup that may not find
anything, a configuration that may be missing, a user who may not be
logged in. Use
std::optionalor an error. - When the interface returns values, and the null version would have to invent them.
Object Pool
- When no one has measured a problem. “Allocation is slow” is not a measurement.
- For small, cheap objects, where the allocator is already fast and the pool’s lifetime rules cost more than they save.
- When one long-lived object, a
reserve, or a memory resource would do.
Common mistakes
Section titled “Common mistakes”- A Null Object for a query. Returning a “null customer”, “null price”, or “guest user” turns “not found” into a believable wrong answer.
- Using a Null Object for a required dependency. If the program cannot do its job without the real object, failing early is better than doing nothing quietly.
- Comparing against the Null Object. If code checks “is this the null one?”, the pattern has not removed any checks.
- A pool without a handle. A pool whose callers must call
release(buffer)by hand leaks a buffer on every earlyreturnand every exception. The lease’s destructor is what makes the pool safe. - Copyable handles. A handle that can be copied returns its object twice.
- Not resetting returned objects. The next borrower sees the last borrower’s data or state.
- A pool destroyed before its leases. Destroying the pool while leases are alive leaves them pointing at freed memory.
- Adding a pool “for performance” with no before-and-after measurement, and so never learning whether it helped.
When the requirements change
Section titled “When the requirements change”- The logger needs a level (“only warnings”): add a
levelto the real loggers, or a filtering logger that wraps another. The Null Object still discards everything and needs no level. - A caller needs to know whether logging is on, to skip building an
expensive message: an
enabled()function on the interface, where the Null Object returnsfalse, is still honest, becausefalseis the true answer. - The pool must be used from several threads: give each thread its
own pool, or add a mutex to
try_acquireandgive_back, and measure the contention. A lease may then end on a different thread from the one that acquired it. - Messages vary in size: several pools of different sizes, or a memory resource, rather than one pool of the largest size.
- Callers must wait for a buffer instead of getting
std::nullopt: a blockingacquirewith a condition variable and a timeout. That is a concurrency design, covered by the planned pages on thread safety and bounded queues.
C++ notes
Section titled “C++ notes”std::optional<Lease>works with a move-onlyLease. ReturningLease{*this, index}fromtry_acquireconstructs the optional from the temporary by moving it.- A move-only type can be stored in a
std::vector, as the third test shows. Its move constructor isnoexcept, which lets the vector keep its strong exception guarantee when it grows. - A common alternative handle is
std::unique_ptr<T, Deleter>, whose deleter returns the object to the pool instead of deleting it. It gives the same move-only ownership with less code. The differences: the object must be reachable as aT*, andunique_ptr::release()lets a caller take the object out of the pool’s control by mistake, which aLeasedoes not offer. assertis removed whenNDEBUGis defined, as it usually is in release builds. Do not rely on it for checks that must always run.
Exercise: Pool, Null Object, or neither?
For each situation, decide whether a pool, a Null Object, both, or neither is justified, and what you would check or measure first. The numbers are assumptions for the exercise, not measurements.
- A game creates about 2,000 small
Bulletobjects a second and destroys them a moment later. A profiler on the release build shows about 1% of frame time in allocation. - A server receives messages into freshly allocated 64 KB buffers, thousands a second. A profiler on the release build, under a realistic load, shows about a third of the time in allocating, zeroing, and freeing them.
- A web service opens a database connection for every request. Each connection takes a network round trip and a login to open.
- A parser builds a new
std::stringfor every token of a large file. - A report generator has an optional
ProgressListenerthat is called after each page. Most callers pass none. - A checkout service has a
NullPaymentGatewaythat returns “paid” and is used when no gateway is configured.
Show the explained answer
- Neither, for now. 1% of frame time is not where the time goes.
If the cost grows, first try keeping the bullets by value in one
std::vectorand reusing its slots: a simple form of pooling with no handles and no separate allocations. - A pool is plausible. The allocation share is large, and the
buffers are big and all the same size. Before building it, find out
how much of that third is zeroing. If the code fills each buffer
anyway,
std::make_unique_for_overwrite<char[]>(n)(C++20) skips the zeroing without a pool. A pool that wipes on return, like this page’s, keeps that cost, so decide whether these buffers need wiping. Also try one buffer per connection, reused across messages. If you build the pool, measure again under the same load, and decide what an empty pool means: wait, drop, or allocate. - A pool, a connection pool. The cost is the handshake, not memory, so it is visible in the time per request without a profiler. The pool also limits how many connections the service holds, which the database may require. Returned connections must be reset, for example by ending any open transaction.
- Neither, and measure first. Tokens shorter than about 15
characters fit in the small-string buffer of the major standard
libraries, so they allocate nothing. If longer tokens do cost
time, and each token is used before the next is read, reuse one
string with
clear(); or, if tokens are only read, returnstd::string_viewinto the file’s text, which needs no allocation per token, provided the text outlives the views. - A Null Object fits. Progress reports are actions, and “report
nothing” is correct for every caller who passes none. A
std::functionparameter with a do-nothing default is a smaller form of the same idea. - No Null Object. A missing gateway is a configuration error, and “paid” is an invented answer that loses money. Refuse to start, or fail each checkout with an error that names the missing setting. A fake gateway that returns “paid” is fine in a test that chose it on purpose.
Summary
Section titled “Summary”- A Null Object implements an interface by doing nothing, so code that uses the interface needs no null checks. It is correct only when doing nothing is the right answer for every caller, typically for actions such as logging.
- When absence is information the caller must act on, a Null
Object hides a failure. Use
std::optionalor an error instead. - An Object Pool creates expensive objects once and lends them out. It is justified only when measurement shows that creating them matters, or when a fixed limit is useful in itself.
- In C++, a pool should lend objects through a move-only handle that gives the object back in its destructor, and the pool must outlive every handle.
- A pool keeps memory, adds a failure mode, and hides use-after-return bugs from sanitizers unless it poisons returned buffers. Try simpler reuse first, and measure before and after.