How to write singleton pattern in C++?

In C++, implementing the Singleton design pattern can be achieved using the following methods:

class Singleton {
private:
    // 私有构造函数,防止外部创建对象
    Singleton() {}

    // 静态私有成员变量,用于保存单例对象
    static Singleton* instance;

public:
    // 静态公有成员函数,用于获取单例对象
    static Singleton* getInstance() {
        if (instance == nullptr) {
            instance = new Singleton();
        }
        return instance;
    }
};

// 初始化静态成员变量
Singleton* Singleton::instance = nullptr;

In this implementation, setting the constructor to private prevents external creation of objects. By using static member variables and static member functions, a globally unique singleton object can be achieved and accessed through the getInstance function.

It is important to note that this implementation is a simple lazy initialization singleton pattern, where the object is only created when the getInstance function is called for the first time. If thread safety is needed, locks can be used to ensure only one thread can create the object.

class Singleton {
private:
    // 私有构造函数,防止外部创建对象
    Singleton() {}

    // 静态私有成员变量,用于保存单例对象
    static Singleton* instance;
    
    // 静态私有成员变量,用于加锁
    static std::mutex mtx;

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;

In this implementation, std::mutex is used to achieve thread safety. When the getInstance function is called for the first time, std::lock_guard is used to lock the mtx, ensuring that only one thread can create the object.

bannerAds