Singleton
A singleton is a type that has exactly one instance for the process (or the thread). In C++ the usual form is a function-local static, which is initialised once and is thread-safe since C++11. Prefer passing dependencies over a hidden global.
Detailed Explanation
A logger, a metrics sink, a type-id registry: you want one of them. The singleton pattern packages that as T::instance(). Callers do not construct T. The constructor is private.
The Meyers singleton is the form that is correct in modern C++:
T& instance() {
static T t;
return t;
}
The static local is initialised the first time control passes the declaration. After C++11 that initialisation is thread-safe: two threads racing the first call wait, one constructs, both proceed. Destruction happens after main returns, in reverse order of completion of initialisation.
The anti-patterns: a file-scope T g; (static initialisation order fiasco across translation units), a raw pointer you new and never delete, a std::call_once plus a leaked pointer, a Meyer singleton that calls another Meyer singleton from a destructor (destruction order can already have run).
Singletons are globals with a class costume. They hide dependencies, they make tests replace implementations only with link-time or #ifdef tricks, and they serialise state across the process. A function that takes Logger& is easier to test than one that calls Logger::instance(). Use a singleton when the object is genuinely unique and plumbing an argument through twenty layers is worse than the hiding. Even then, consider a context object you pass once at the top.
instance() returning a reference is better than returning a pointer: there is no null. Returning a shared_ptr suggests the instance might die while you hold it, which fights "there is one".
Subclassable singletons (a virtual instance that returns a mock) are a test hack. Prefer injecting an interface.
Process-wide mutable singletons need their own mutex. Thread-safe construction is not thread-safe use.
Code Examples
#include <iostream>
#include <string>
class Log {
public:
static Log& instance() {
static Log g;
return g;
}
void write(const std::string& line) { std::cout << line << '\n'; }
Log(const Log&) = delete;
Log& operator=(const Log&) = delete;
private:
Log() = default;
};
int main() {
Log::instance().write("boot"); // prints: boot
}Common Gotchas
Using another singleton in a destructor
destruction order of function-local statics is reverse of completion. The other instance may already be dead.
Thread-safe init ≠ thread-safe methods
guard mutable state.
Tests and singletons fight
reset APIs become part of the production type. Inject instead.
A heap singleton you never destroy
sanitizers report leaks. A function-local static is destroyed; accept that or use `noleak` abstractions carefully.