How to implement the Singleton pattern in C++?

There are several ways to implement the Singleton pattern in C++.

  1. Hungry Singleton Pattern: The singleton object is created at program startup and a global access point is provided.
class Singleton {
private:
    static Singleton* instance;
    Singleton() {}

public:
    static Singleton* getInstance() {
        return instance;
    }
};

Singleton* Singleton::instance = new Singleton();
  1. Lazy initialization singleton pattern: the singleton object is only created upon the first access.
class Singleton {
private:
    static Singleton* instance;
    Singleton() {}

public:
    static Singleton* getInstance() {
        if (instance == nullptr) {
            instance = new Singleton();
        }
        return instance;
    }
};

Singleton* Singleton::instance = nullptr;
  1. Double-checked locking singleton pattern: creates a singleton object only on the first access, and ensures thread safety using double-checked locking mechanism.
#include <mutex>

class Singleton {
private:
    static Singleton* instance;
    static std::mutex mtx;
    Singleton() {}

public:
    static Singleton* getInstance() {
        if (instance == nullptr) {
            std::lock_guard<std::mutex> lock(mtx);
            if (instance == nullptr) {
                instance = new Singleton();
            }
        }
        return instance;
    }
};

Singleton* Singleton::instance = nullptr;
std::mutex Singleton::mtx;

These are common ways to implement the Singleton pattern, choose one based on specific requirements and thread safety.

bannerAds