Skip to content

Singleton (and why to avoid it)

Difficulty: Intermediate

Key concepts

  • singleton pattern
  • function-local static
  • hidden dependency
  • global mutable state
  • initialization order
  • composition root
  • What Singleton is meant to do, and how to write one correctly in modern C++: a function-local static, which C++ initializes once, even when several threads arrive at the same time.
  • Why it usually hurts, shown with code and tests: a hidden dependency, tests that share state, data races when the object can change, and problems with start-up and shut-down order.
  • How to replace it: create the object once, in main, and pass it to the code that needs it.
  • The few cases where a single, global object is acceptable.

A small online shop prices shopping carts. The prices depend on a few settings that the shop owner keeps in a file, shop.conf.

Requirements:

  1. FR-1 A cart’s price is its subtotal, plus tax at the shop’s tax rate, plus a shipping charge, which is free when the subtotal reaches a threshold.
  2. FR-2 The settings are read from shop.conf once, at start-up, and checked. A mistake in the file stops the program with a message that names the line.
  3. FR-3 Tests price carts with their own settings, in any order, and without affecting each other.
  4. FR-4 (planned for next quarter) The same program will also run an outlet shop, with its own tax and shipping settings, next to the main shop.

Where Singleton shows up in requirements. Listen for “there is only one” (one configuration, one logger, one database, one connection pool) and “it must be reachable from anywhere”. Both deserve a question. “Only one” is usually true of this program today, not a law about the type: FR-4 already plans a second shop. And “reachable from anywhere” usually means “I do not want to pass it as a parameter”. That is the convenience Singleton offers, and its whole cost.

Singleton makes a class that can have only one object, and gives the whole program one global way to reach it. The usual C++ form keeps the object in a function-local static:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

before.hpp
// The one configuration object in the program, written as a Singleton.
// Three things together make "only one" true: the constructor is private
// (nobody outside can make a Config), copying is deleted (nobody can
// duplicate the one there is), and instance() is the only way to reach it.
// `final` means no class can inherit from Config either.
class Config final {
public:
// `static` means "belongs to the class, not to an object", so it is
// called as Config::instance() with no Config in hand. It returns a
// reference (Config&), never a copy: every caller gets the same object.
static Config& instance(); // created on the first call
// `= delete` removes the copy constructor and copy assignment, so a
// line such as `Config copy = Config::instance();` does not compile.
Config(const Config&) = delete;
Config& operator=(const Config&) = delete;
// Replaces every setting. A singleton cannot take constructor
// arguments from its callers, so the settings arrive later, here.
// parse_settings builds a fresh ShopSettings from the text (defaults
// for anything the text does not mention), which is then assigned over
// the old one. If the text is bad, parse_settings throws
// std::invalid_argument before the assignment, so the old settings stay.
void load(std::string_view text) { settings_ = parse_settings(text); }
// A read-only reference to the settings inside the one Config. It
// stays valid for the whole program, but a later load() changes what
// it refers to.
const ShopSettings& settings() const { return settings_; }
private:
// Private, so only Config's own members (here, instance()) can create
// a Config. `= default` asks for the ordinary constructor, which gives
// settings_ the default values written in ShopSettings.
Config() = default;
ShopSettings settings_;
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

before.cpp
// Hands back the one Config, creating it on the first call.
Config& Config::instance() {
// A function-local static: created the first time control passes
// here, once, even if several threads arrive at the same time.
// Unlike an ordinary local variable, it is not destroyed when the
// function returns: it lives until after main returns. Later calls
// skip the creation and reuse the same object. instance() is a member
// of Config, so it is allowed to call the private constructor.
static Config config;
// Returning a reference to a local would normally dangle; here it is
// safe, because a static local outlives every call.
return config;
}
  • The constructor is private, so no code outside the class can create a second Config. The copy operations are deleted, so no code can copy the one there is.
  • instance() holds the object in a function-local static. It is created the first time control passes through its declaration, and destroyed after main returns.
  • The creation is thread-safe. Since C++11, if several threads reach the declaration while the object is still being created, the others wait until it is done, and the constructor runs once. If the constructor throws, the object is not created, and the next call tries again. (A scratch program in which sixteen threads called such a function with a slow constructor built the object once.) Hand-written locking, such as the “double-checked locking” found in older code, is not needed. This form is often called a Meyers singleton.
  • load() exists because of the pattern. Callers cannot pass arguments to a constructor they never call, so the settings must arrive later, through a member function. Until something calls load(), the object holds the defaults.

The code that prices a cart now reaches the settings from anywhere:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

before.hpp
// The price of a cart in cents: subtotal, plus tax, plus shipping.
// The signature says nothing about tax or shipping: the settings it needs
// are fetched inside the function, from the singleton.
int total_cents(const Cart& cart);

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

before.cpp
// Prices a cart with whatever settings the singleton holds at the moment
// of the call. Nothing in the parameter list shows that dependency.
int total_cents(const Cart& cart) {
// A reference to the settings inside the one Config, not a copy: a
// load() anywhere in the program before this call changes the answer.
const ShopSettings& settings = Config::instance().settings(); // hidden input
// Add up price times quantity for every line of the cart.
int subtotal = 0;
for (const Line& line : cart) {
subtotal += line.unit_cents * line.quantity;
}
// Tax, rounded to the nearest cent. Integer division drops the
// fraction, so adding 50 (half of 100) first rounds halves up: at 19%,
// 2499 * 19 = 47481, and (47481 + 50) / 100 is 475, not 474.
const int tax = (subtotal * settings.tax_percent + 50) / 100;
// `?:` picks 0 (free shipping) once the subtotal reaches the
// threshold, and the normal shipping charge below it.
const int shipping =
subtotal >= settings.free_shipping_from_cents ? 0 : settings.shipping_cents;
return subtotal + tax + shipping;
}

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// Two steps that must happen in this order, and nothing in the code
// says so: first fill the one Config from the settings text (19% tax,
// 4.99 shipping), then price the cart, which reads that Config.
before::Config::instance().load(shop_conf);
std::cout << "before: total " << money(before::total_cents(cart)) << '\n';

It works, and it is short. The rest of this section is what it costs.

int total_cents(const Cart& cart) says that the price depends on the cart. It also depends on three settings, and nothing in the signature says so. To learn what a function depends on, a reader must now read its body, and the body of everything it calls. A function that calls total_cents depends on the settings too, also invisibly.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_checkout.cpp
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure
// if the condition is false, and LLD_CHECK_EQ(actual, expected) records a
// failure, printing both values, if they are not equal. They come from the
// site's small test header, lld_test.hpp. `cart` is defined once at the top
// of this file: a book at 19.99 and two pens at 2.50, a subtotal of 24.99.
//
// The answer depends on state that is not in the call.
// Sets up: the Config as it is when this test starts (the defaults, 20%
// tax, if no earlier test changed it). Proves: the very same call,
// total_cents(cart), returns two different totals (34.98, then 29.98)
// once someone, anywhere, loads different settings into the singleton.
LLD_TEST(before_the_same_call_gives_different_answers) {
const int with_defaults = before::total_cents(cart);
before::Config::instance().load("tax_percent = 0\n"); // a test of tax-free orders
const int tax_free = before::total_cents(cart);
LLD_CHECK(with_defaults != tax_free);
// Nothing undoes the load. Every test that runs after this one in the
// same process would see tax_percent = 0, so the test must restore the
// defaults by hand, and must not throw before it does.
// Loading empty text gives ShopSettings{}, the defaults, which is only
// right if the Config held the defaults when the test started.
before::Config::instance().load("");
LLD_CHECK_EQ(before::total_cents(cart), with_defaults);
}
// `&` takes the address of the object instance() returns. Two calls giving
// the same address means both returned the very same Config, not two
// equal copies.
LLD_TEST(before_there_is_only_ever_one) {
LLD_CHECK(&before::Config::instance() == &before::Config::instance());
}
  • The same call gives different answers. total_cents(cart) returned one price, then, with no change to its argument, another. Its result depends on state that is not in the call.
  • Every test sees every other test’s changes. The first test must restore the defaults by hand. If it throws or returns early before the restore line (for example, through a test framework’s fatal assertion), every later test that prices through the singleton runs with a tax rate of 0, and may fail for a reason unrelated to its own code.
  • FR-3 fails. Tests cannot each have their own settings, and they cannot run at the same time in one process.

The outlet needs other settings in the same program. A singleton cannot have two objects; the type itself forbids it. Every function that calls Config::instance() would need to change to learn which shop it is pricing for.

The function-local static makes creation thread-safe, and nothing else. A load() in one thread while another thread prices a cart is a data race, which is undefined behaviour; ThreadSanitizer (Clang 14) reported exactly that for this example’s Config in a scratch program. Making the singleton safe would mean a mutex held by load() and by every read, with settings() returning a copy instead of a reference, for data that, in this program, never changes after start-up.

Sort the singleton’s parts by what they are, rather than by “the one configuration object”:

Data or job What it really is Where it goes
tax percent, shipping, free-shipping threshold plain data, checked once ShopSettings, a struct of values with defaults
reading and checking shop.conf’s text a pure function of the text parse_settings(text), a free function with no state
pricing a cart behaviour that needs the settings Checkout::price(cart), a const member function
“which settings does this checkout use?” a constructor parameter Checkout’s constructor; stored as a data member
“there is only one” a decision of this program, not of the type main, which creates one Checkout for each shop it runs
reading the file, choosing what goes where start-up main, the composition root

Each row now has an owner you can see in the code. The settings become a value. The parser keeps no state, so it can be tested with a string. And “only one” moves from the type, where it was enforced everywhere, to main, where it is one line that can change.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

settings.hpp
// The shop's settings, as plain data. Amounts are in cents.
// No singleton, no file reading, no behaviour: just three numbers that can
// be copied, compared, and passed around like any value. The `= ...` after
// each member is its default, used whenever a ShopSettings is made without
// a value for that member: ShopSettings{} is 20% tax, 4.99 shipping, and
// free shipping from 50.00.
struct ShopSettings {
int tax_percent = 20;
int shipping_cents = 499;
int free_shipping_from_cents = 5000;
// `= default` asks the compiler to write ==, comparing the members one
// by one. The tests use it to compare whole settings in one check.
bool operator==(const ShopSettings&) const = default;
};
// Reads "name = value" lines; blank lines and lines starting with '#' are
// skipped, and a setting that is not given keeps its default. Throws
// std::invalid_argument, naming the line, for an unknown name, a value
// that is not a whole number, or a value out of range.
// A free function with no hidden state: the same text always gives the
// same settings, so it can be tested with nothing but a string. The text is
// a std::string_view, a read-only view of characters owned by the caller.
ShopSettings parse_settings(std::string_view text);

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

checkout.hpp
// The result of pricing one cart, every amount in cents. Returning all
// four parts (not just the total) lets the caller print them and lets a
// test check each one. The compiler-written == compares all four.
struct Receipt {
int subtotal_cents = 0;
int tax_cents = 0;
int shipping_cents = 0;
int total_cents = 0;
bool operator==(const Receipt&) const = default;
};
// Prices carts with the settings it was given, and no others.
// The dependency the singleton hid is now a constructor parameter: there
// is no constructor without settings, so a Checkout cannot exist until
// someone decides which settings it uses.
class Checkout final {
public:
// `explicit` stops a bare ShopSettings from silently turning into a
// Checkout. The settings arrive by value and are copied into settings_,
// so the checkout owns its own copy and does not depend on how long
// the caller's settings live.
explicit Checkout(ShopSettings settings) : settings_{settings} {}
// Prices one cart. `const`: pricing never changes the checkout, so the
// same cart priced twice on the same checkout gives the same receipt.
Receipt price(const Cart& cart) const;
const ShopSettings& settings() const { return settings_; }
private:
ShopSettings settings_; // a copy: small, and cannot change under us
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

checkout.cpp
// The same arithmetic as before::total_cents, step by step into a Receipt.
// The only difference is where the settings come from: settings_, the copy
// this checkout was built with, instead of a global object.
Receipt Checkout::price(const Cart& cart) const {
Receipt receipt; // every amount starts at 0
// int cents are enough for a shop basket. A system that adds up large
// amounts would use std::int64_t or check for overflow.
for (const Line& line : cart) {
receipt.subtotal_cents += line.unit_cents * line.quantity;
}
// Tax rounded to the nearest cent: adding 50 before the integer
// division by 100 rounds halves up instead of always rounding down.
receipt.tax_cents = (receipt.subtotal_cents * settings_.tax_percent + 50) / 100;
// Free shipping (0) from the threshold up, the normal charge below it.
receipt.shipping_cents = receipt.subtotal_cents >= settings_.free_shipping_from_cents
? 0
: settings_.shipping_cents;
receipt.total_cents = receipt.subtotal_cents + receipt.tax_cents + receipt.shipping_cents;
return receipt;
}
How this code works: Checkout::price, for the shop and the outlet

price fills in a Receipt in four steps, each using the result of the one before:

  1. Subtotal. Add unit_cents * quantity for every line.
  2. Tax. (subtotal * tax_percent + 50) / 100. Dividing two ints throws the fraction away, so on its own / 100 would always round down. Adding 50 first (half of 100) makes anything from half a cent up round up instead.
  3. Shipping. 0 if the subtotal is at least free_shipping_from_cents, otherwise shipping_cents. The comparison is >=, so a subtotal exactly at the threshold ships free.
  4. Total. The sum of the three.

The cart in main is one book at 1999 cents and two pens at 250 cents. The shop’s text sets 19% tax and 499 shipping, and keeps the default free-shipping threshold of 5000. The outlet’s text sets 20% tax and a threshold of 2000, and keeps the default 499 shipping.

Step Shop (19%, free from 5000) Outlet (20%, free from 2000)
subtotal 1999 × 1 + 250 × 2 = 2499 2499
tax (2499 × 19 + 50) / 100 = 47531 / 100 = 475 (2499 × 20 + 50) / 100 = 50030 / 100 = 500
shipping 2499 is below 5000: 499 2499 is at least 2000: 0
total 2499 + 475 + 499 = 3473 2499 + 500 + 0 = 2999

These are the totals 34.73 and 29.99 in the program’s output, in the Check section below. The singleton version, before::total_cents, does exactly the same arithmetic; it differs only in reading the percentages and amounts from Config::instance() at the moment it runs, where price reads settings_, the copy this checkout was built with.

  • The dependency is in the constructor. A Checkout cannot be created without settings (there is no default constructor), and a reader sees what it needs from its declaration.
  • The settings are stored by value. ShopSettings is three ints, so a copy is cheap, and the checkout does not depend on the lifetime of any other object. Storing const ShopSettings& would also work, but then the settings must outlive the checkout. A line such as Checkout checkout{parse_settings(text)}; would compile and leave the checkout holding a reference to a temporary that is destroyed at the end of the line.
  • price() depends only on the cart and the checkout, so the same call on the same checkout always gives the same answer.
  • parse_settings is a free function. It has no state to share, so tests can call it with any text, in any order. A setting left out keeps its default, and a setting given twice takes the later line’s value.

class ShopSettings

a struct: plain data with defaults

Data members

  • int tax_percent = 20;
  • int shipping_cents = 499;
  • int free_shipping_from_cents = 5000;

class Checkout final

Data members

  • ShopSettings settings_; a copy, given to the constructor

Member functions

  • explicit Checkout(ShopSettings settings);
  • Receipt price(const Cart& cart) const; depends on the cart and settings_ only

namespace global

not a real namespace: free functions at file scope

Functions

  • ShopSettings parse_settings(std::string_view text); throws std::invalid_argument naming the line
After the refactor: plain data, a pure function, and a class that takes its settings

The outline leaves out Receipt (four amounts in cents), Cart, Checkout::settings(), and the defaulted operator== on ShopSettings and Receipt that the tests use.

Before, the pricing code reaches a global; after, main reads the settings once and passes them to each checkout
Text description of the diagram

Two parts, before and after. A dashed arrow means “uses”, and a solid arrow means “creates”. The arrow from Before to After shows the refactor. Before: main calls load with the contents of shop.conf on Config::instance(), one global object. total_cents(cart) reads that object, which its signature does not show. The tests also call load on the same object and must restore it by hand. After: main calls parse_settings on the contents of shop.conf to make the shop’s ShopSettings, then creates a Checkout for the shop with those settings and a second Checkout, for the outlet, with other settings. Each test creates its own Checkout with its own settings. Nothing is global.

Diagram source (Mermaid)
flowchart TB
subgraph Before
  BM["main"] -.->|"load(shop.conf)"| BC["Config::instance()<br/>one global object"]
  BT["total_cents(cart)"] -.->|"reads, unseen<br/>in its signature"| BC
  BX["tests"] -.->|"load(...), restore by hand"| BC
end
subgraph After
  AM["main"] -->|"parse_settings(shop.conf)"| AS["ShopSettings<br/>for the shop"]
  AM -->|"creates, with the settings"| AC["Checkout shop"]
  AM -->|"creates, with other settings"| AO["Checkout outlet"]
  AX["each test"] -->|"creates its own"| AT["Checkout<br/>test settings"]
end
Before --> After
Object Owner Lives
before: the Config nobody you can see: a static from the first instance() call until after main returns
after: each ShopSettings the Checkout that holds it, by value as long as that checkout
after: each Checkout main, or a test, as a local variable until the end of its scope

The singleton’s lifetime is the program’s, and its creation and destruction happen out of sight. After the refactor every object is a local variable of a function you can read.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// main is the one place that reads the settings and decides who gets them.
// parse_settings returns a temporary ShopSettings; the Checkout copies
// it into its own member, so nothing dangles when the temporary is gone.
const Checkout checkout{parse_settings(shop_conf)};
print("shop", checkout.price(cart));
// A second shop in the same program, with its own settings.
// Here "\n" ends each line: 20% tax and free shipping from 20.00, with
// shipping_cents left at its default of 499.
const Checkout outlet{parse_settings("tax_percent = 20\nfree_shipping_from_cents = 2000\n")};
print("outlet", outlet.price(cart));
// Bad settings text: line 2 names a setting that does not exist, so
// parse_settings throws std::invalid_argument, and the catch prints its
// message (what()), which names the line.
try {
parse_settings("tax_percent = 19\ntax = 7\n");
} catch (const std::invalid_argument& error) {
std::cout << "error: " << error.what() << '\n';
}
Expected output
before: total 34.73
shop: subtotal 24.99, tax 4.75, shipping 4.99, total 34.73
outlet: subtotal 24.99, tax 5.00, shipping 0.00, total 29.99
error: line 2: unknown setting 'tax'

Read the output against the requirements:

  • The shop’s receipt gives the same total as the singleton version for this cart, 34.73 (FR-1). The pricing code is the same; only the way it gets the settings changed.
  • The outlet’s receipt, with 20% tax and free shipping from 20.00, is priced in the same program, next to the shop (FR-4).
  • A mistake in the settings text is reported with its line number (FR-2).

The tests create their own checkouts and settings, so they share nothing and can run in any order (FR-3):

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_checkout.cpp
// Each test below makes its own Checkout from its own ShopSettings, so no
// test can see another's settings, and they can run in any order. `cart`
// is the file's shared cart, which no test changes: a subtotal of 24.99.
// static_assert is checked by the compiler, not when the tests run: this
// file does not compile if Checkout ever gains a constructor that takes
// no settings.
static_assert(!std::is_default_constructible_v<Checkout>); // the settings are required
// ShopSettings{.tax_percent = 10, .shipping_cents = 300} uses designated
// initializers (C++20): it names the members it sets, in declaration order,
// and every member it does not name keeps its default. Here free shipping
// still starts at 50.00, so the 24.99 cart pays the 3.00 shipping. Tax is
// (2499 * 10 + 50) / 100 = 250, and the total 2499 + 250 + 300 = 3049.
LLD_TEST(a_checkout_uses_the_settings_it_was_given) {
const Checkout checkout{ShopSettings{.tax_percent = 10, .shipping_cents = 300}};
const Receipt expected{.subtotal_cents = 2499,
.tax_cents = 250,
.shipping_cents = 300,
.total_cents = 3049};
LLD_CHECK(checkout.price(cart) == expected);
}
// Two checkouts with different settings exist at the same time, which the
// singleton made impossible. Pricing one does not affect the other:
// (2499 * 20 + 50) / 100 = 500 cents of tax, and 0 at 0%.
LLD_TEST(two_checkouts_with_different_settings_live_side_by_side) {
const Checkout taxed{ShopSettings{.tax_percent = 20}};
const Checkout tax_free{ShopSettings{.tax_percent = 0}};
LLD_CHECK_EQ(taxed.price(cart).tax_cents, 500);
LLD_CHECK_EQ(tax_free.price(cart).tax_cents, 0);
}
// The boundary, checked from both sides with the 2499-cent cart: a
// threshold of exactly 2499 gives free shipping (the comparison is >=),
// and one cent more, 2500, charges the default 499.
LLD_TEST(shipping_is_free_from_the_threshold_up) {
const Checkout checkout{ShopSettings{.free_shipping_from_cents = 2499}};
LLD_CHECK_EQ(checkout.price(cart).shipping_cents, 0);
const Checkout stricter{ShopSettings{.free_shipping_from_cents = 2500}};
LLD_CHECK_EQ(stricter.price(cart).shipping_cents, 499);
}
// The parser is tested with plain strings, no file and no shared object.
// The text has a comment line, a blank line, and a line with spaces around
// it and a Windows-style "\r" at the end; only tax_percent changes, and the
// other two settings keep their defaults. Empty text gives all defaults.
LLD_TEST(parse_reads_settings_and_keeps_defaults_for_the_rest) {
const ShopSettings settings = parse_settings("# comment\n\n tax_percent = 7 \r\n");
const ShopSettings expected{.tax_percent = 7};
LLD_CHECK(settings == expected);
LLD_CHECK(parse_settings("") == ShopSettings{});
}
// error_of (a helper at the top of this file) calls parse_settings and
// returns the message of the std::invalid_argument it throws, or "parsed"
// if it throws nothing. One check per kind of mistake: an unknown name, a
// value that is not a whole number (on line 2, after an empty first line),
// a value out of range, a line with no '=', and an empty value.
LLD_TEST(parse_names_the_line_of_each_kind_of_mistake) {
LLD_CHECK_EQ(error_of("tax = 7"), std::string{"line 1: unknown setting 'tax'"});
LLD_CHECK_EQ(error_of("\ntax_percent = 7%"), std::string{"line 2: '7%' is not a whole number"});
LLD_CHECK_EQ(error_of("tax_percent = 120"),
std::string{"line 1: tax_percent must be between 0 and 100"});
LLD_CHECK_EQ(error_of("tax_percent 7"), std::string{"line 1: expected name = value"});
LLD_CHECK_EQ(error_of("shipping_cents ="), std::string{"line 1: '' is not a whole number"});
}

A global object is not always wrong. It is acceptable when it causes none of the problems above:

  • It is immutable after it is made, and it does not depend on configuration. A table of constants computed once, returned from a function-local static const, is a good use of a function-local static: there is no state to share, and tests have no reason to replace it.
  • It is a genuine, process-wide resource, and its effects do not change results. std::cout is a global object. A log sink that only adds output is often treated the same way, though tests that check log messages will want to replace it.
  • The platform makes it one per process, such as a hardware device that really exists once. Even then, wrap it in an object that main creates, and pass that, so code that uses it can be tested with a fake. A signal handler is the narrow exception: it receives no arguments, so it can reach only globals, and it may safely touch only a volatile std::sig_atomic_t or a lock-free atomic flag that normal code then reads.

The test is simple: would any test, now or later, want a different one? If yes, pass it in.

Honesty about the alternative:

  • More parameters. Every class that needs the settings takes them in its constructor, and code that creates those classes must have the settings to give. In a deep call chain this is tedious.
  • Mitigations: pass dependencies to constructors, not to every function; group several related dependencies in one struct; and create the long-lived objects in one place, main, so most code receives objects that are already set up. See dependency injection.

These costs are visible in the code, where you can see and manage them. A singleton’s costs are invisible until a test fails for no reason, or a second shop is needed.

  • A singleton for convenience. “Many classes need it” is a reason to pass it, not a reason to make it global.
  • A set_instance() for tests. A singleton whose object tests can swap is still a global: tests still share it, and must still restore it.
  • A class of only static members, or several objects that share static data (sometimes called a monostate). The syntax differs; the global state and all its costs are the same.
  • A service locator, a global registry from which code fetches its dependencies by type or name. It is a singleton that holds other objects, and hides every dependency behind one.
  • Hand-written double-checked locking around a pointer. A function-local static already does this correctly.
  • “A third shop.” After the refactor: one more parse_settings and one more Checkout in main. With the singleton, every caller of Config::instance() would have to change.
  • “Reload the settings while the program runs.” Now the settings really are shared and changing. Make the sharing explicit: keep a std::shared_ptr<const ShopSettings> behind a mutex in an object that main creates, and have checkouts take a fresh copy of the pointer at the start of each sale. A sale that started with the old settings finishes with them, and a reload never changes settings while they are in use.
  • “Log every sale.” Pass a logger to Checkout’s constructor, exactly as the settings are passed. Tests can pass one that records messages, and check them.

Exercise: Remove a singleton

A coupon checks whether it has expired by asking a clock singleton:

// A singleton that tells the time: the same shape as Config above, with
// a private constructor and one static instance() that returns the one
// object (the copy operations are left out here to keep it short).
class Clock final {
public:
static Clock& instance();
// The current date and time, read from the computer's real clock.
// A time_point is one moment in time.
std::chrono::system_clock::time_point now() const {
return std::chrono::system_clock::now();
}
private:
Clock() = default;
};
// A discount code that stops working at a fixed moment.
class Coupon final {
public:
Coupon(std::string code, std::chrono::system_clock::time_point expires);
// Valid while "now" is before the expiry moment. "Now" comes from the
// clock singleton, read inside the function.
bool is_valid() const { return Clock::instance().now() < expires_; }
private:
std::string code_;
std::chrono::system_clock::time_point expires_;
};
  1. Why is is_valid() hard to test? Describe a test you would want to write and cannot.
  2. Remove the singleton with the smallest change that makes is_valid() testable.
  3. A Checkout reads the time in many places (coupons, opening hours, receipts). Suggest a design for it, and say where the real clock is created.
Show the explained answer

1. The result depends on the real time, which a test cannot set. A test that a coupon is valid one second before it expires, and invalid at the moment it expires, would have to run at exactly those moments. A test can set the expiry relative to the current time, but the clock moves between building the coupon and checking it, so the boundary cases pass or fail depending on timing.

2. Pass the time in. is_valid then depends only on its argument and the coupon:

// A short name for the long type of "a moment in time".
using Time = std::chrono::system_clock::time_point;
// The caller says what time it is; the coupon only compares.
bool is_valid(Time now) const { return now < expires_; }
// in a test, with Time t0{} and std::chrono_literals:
// Time t0{} is a fixed moment the test chooses (the clock's starting
// point), and std::chrono_literals is what lets 24h mean "24 hours".
const Coupon coupon{"SPRING", t0 + 24h}; // expires 24 hours after t0
LLD_CHECK(coupon.is_valid(t0 + 23h)); // an hour before: still valid
LLD_CHECK(!coupon.is_valid(t0 + 24h)); // at the expiry moment: not valid (< is strict)

The Clock class is no longer needed for coupons at all. The caller reads the clock once and passes the time, which also makes every check in one sale agree on what time it is.

3. When many functions need the time, inject a clock interface instead:

// An interface: "something that can tell the time". `= 0` means every
// real clock must write its own now(). The virtual destructor makes it
// safe to destroy a clock through a Clock pointer or reference.
class Clock {
public:
virtual ~Clock() = default;
virtual Time now() const = 0;
};
// The real clock, which main creates once. A test would pass its own
// class instead, whose now() returns whatever time the test sets.
class SystemClock final : public Clock {
public:
Time now() const override { return std::chrono::system_clock::now(); }
};
// The checkout is given a clock instead of finding one. It keeps a
// reference, not a copy: Clock is abstract (it has a `= 0` function), so a
// member of type Clock cannot exist, and the reference lets the checkout
// use whichever clock it was given, the real one or a test's.
class Checkout final {
public:
explicit Checkout(const Clock& clock) : clock_{clock} {}
// A const Clock& also binds to a temporary, as in
// Checkout checkout{SystemClock{}}; this deleted overload is a better
// match for a temporary, so that line fails to compile instead.
Checkout(const Clock&&) = delete; // a temporary clock would dangle
// Reads the time from the clock it was given, and lets the coupon judge.
bool accepts(const Coupon& coupon) const { return coupon.is_valid(clock_.now()); }
private:
const Clock& clock_; // must outlive the checkout
};

main creates the one SystemClock and passes it to the checkout; tests pass a FixedClock that returns a time the test chose. There is still only one real clock in the program, because main made one, not because the type forbids a second. Storing a reference means the clock must outlive the checkout; main’s local variables do, if the clock is declared before the checkout. The deleted constructor stops Checkout{SystemClock{}} from compiling.

  • Abstract Factory: a concrete factory is often made a singleton. It does not need to be; create one in main and pass it in. See Abstract Factory.
  • Facade: a facade over a subsystem is another common singleton. The same refactor applies. See Facade.
  • Dependency injection is the general technique this page uses to remove the singleton. See dependency injection.
  • When patterns hurt shows Singleton alongside other unneeded patterns, and the costs of shared mutable state.
  • Singleton gives a class one object and the whole program one global way to reach it. In C++, write it with a function-local static, whose creation is thread-safe.
  • Its costs: dependencies hidden from every signature, tests that share one object, data races when it can change, start-up and shut-down order traps, and a type that forbids the second object the program later needs.
  • The replacement: plain data, pure functions, and classes that take their dependencies in their constructors, all created in main.
  • “Only one” is a decision of the program. Make it in main, not in the type.
  • A global is acceptable when it is immutable, or has no effect on results, and no test would ever want a different one.