How is the implementation of the singleton design pattern in C++ done?
There are multiple ways to implement the singleton pattern in C++, here are two commonly used methods:
- The Singleton pattern with lazy initialization.
class Singleton {
private:
static Singleton* instance;
Singleton() {} // 私有构造函数
public:
static Singleton* getInstance() {
if (instance == nullptr) {
instance = new Singleton();
}
return instance;
}
};
Singleton* Singleton::instance = nullptr;
In the eager singleton pattern, the instance is already created when the program starts, and the getInstance() method directly returns that instance. If delayed instantiation is needed, it can be implemented by adding logic for checking and instantiation within the getInstance() method.
- Lazy Singleton Design Pattern
class Singleton {
private:
static Singleton* instance;
Singleton() {} // 私有构造函数
public:
static Singleton* getInstance() {
if (instance == nullptr) {
instance = new Singleton();
}
return instance;
}
};
Singleton* Singleton::instance = nullptr;
In the lazy singleton design pattern, the instance is created when the getInstance() method is first called, and attention should be paid to the thread safety issues in a multi-threaded environment. Lock mechanism or double-check locking mechanism can be used to ensure thread safety.
It is important to note that both of the above methods require setting the default constructor as private to prevent direct instantiation of objects elsewhere.