The Singleton Pattern in C++
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.
Private constructor
No outside code can create or copy the object — construction passes solely through the static accessor.
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.
Delete copy and assign
Config(const Config&) = delete; plus operator= deleted — the single instance can never be duplicated.
Question every use
Hidden global access resists testing and reasoning — singleton for the truly singular, injection for the merely shared.
#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;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.