CreationalC++verifiedVerified

Singleton Pattern in C++

Ensures a class has only one instance and provides a global point of access to it.

How to Implement the Singleton Pattern in C++

1Step 1: Define the Singleton with deleted copy/move constructors

class AppConfig {
public:
    static AppConfig& instance() {
        static AppConfig inst;
        return inst;
    }

    void set(const std::string& key, const std::string& value) {
        data_[key] = value;
    }

    std::string get(const std::string& key) const {
        auto it = data_.find(key);
        return it != data_.end() ? it->second : "";
    }

2Step 2: Prevent copying and moving

    AppConfig(const AppConfig&) = delete;
    AppConfig& operator=(const AppConfig&) = delete;

private:
    AppConfig() = default;
    std::map<std::string, std::string> data_;
};

3Step 3: Demonstrate usage

int main() {
    AppConfig::instance().set("db_host", "localhost");
    std::cout << AppConfig::instance().get("db_host") << "\n";
}

Singleton Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Singleton Pattern in the Real World

Think of a country’s president. There can only be one at any time. When anyone needs to communicate with the president, they don’t create a new one—they access the existing one through the official channel (the static method).