Learn C++
#include "oopadvanced/singleton.hpp"

The Singleton Pattern in C++

//concept

The Singleton guarantees exactly one instance of a class with global access: private constructor plus a static accessor returning a function-local static (Meyers' Singleton), which C++11 constructs thread-safely on first use. Loggers, configuration stores, and hardware facades are the textbook residents.

Use it sparingly — singletons hide dependencies, complicate testing, and invite global-state sprawl. Prefer dependency injection for most shared services; reserve Singleton for things genuinely singular (the logging sink, the app config) where passing references everywhere costs more clarity than it buys.

//how it works
1

Private constructor

No outside code can create or copy the object — construction passes solely through the static accessor.

2

Function-local static instance

static Config& instance() { static Config c; return c; } — created once on first call, destroyed at program exit, thread-safe since C++11.

3

Delete copy and assign

Config(const Config&) = delete; plus operator= deleted — the single instance can never be duplicated.

4

Question every use

Hidden global access resists testing and reasoning — singleton for the truly singular, injection for the merely shared.

//example
#include <iostream>
#include <string>
 
class Config {
Config() = default;
Config(const Config&) = delete;
Config& operator=(const Config&) = delete;
public:
std::string mode = "release";
static Config& instance() {
static Config c;
return c;
}
};
 
int main() {
Config::instance().mode = "debug";
std::cout << Config::instance().mode << std::endl;
return 0;
}
Output
debug
1Private constructor plus deleted copies make direct construction impossible — only instance() can provide the object.
2First call builds the single Config; the assignment flips its mode to debug.
3The second call returns the same object, so debug prints — one instance, globally reachable.
//use cases
Application-wide configuration and logging sinks
Hardware and driver facades with physically singular resources
Replacing singletons with injected dependencies where testability matters
Thread-safe lazy initialization via function-local statics

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.