Singleton Pattern in C++: Step-by-Step

In C++, the following steps can be used to implement the singleton pattern:

  1. Create a class, and set the constructor and destructor as private to prevent other code from directly creating objects.
  2. Declare a pointer to the class object within the private static members of the class, to store the instance of the singleton object.
  3. Provide a static public method to retrieve an instance of the singleton object. The method should first check if the singleton object’s instance already exists, and if not, create a new instance, store it in a static member, and finally return a pointer to that instance.
  4. One way to ensure only one thread can create an instance in a multi-threaded environment is by using locks.
  5. By defining a private copy constructor and assignment operator function, prevent the creation of new instances through copy constructor and assignment operator functions.
  6. Finally, in the program, you can obtain an instance of the singleton object by calling the static public method and then use that instance for operations.

Here is a simple example code of the singleton design pattern.

class Singleton {
private:
    static Singleton* instance; // 静态成员,保存单例对象的实例
    Singleton() {} // 私有构造函数

public:
    static Singleton* getInstance() {
        if (instance == nullptr) {
            instance = new Singleton();
        }
        return instance;
    }
    // 禁止拷贝构造函数和赋值运算符函数
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;
};

Singleton* Singleton::instance = nullptr; // 对静态成员进行初始化

int main() {
    Singleton* singleton1 = Singleton::getInstance();
    Singleton* singleton2 = Singleton::getInstance();
    
    if (singleton1 == singleton2) {
        cout << "两个对象是同一个实例" << endl;
    }
    else {
        cout << "两个对象不是同一个实例" << endl;
    }
    
    return 0;
}

In the above code, the Singleton class’s singleton object instance is obtained by calling the Singleton::getInstance() method, and then comparing the two pointers to determine if they are the same instance.

bannerAds