Middle
How would you implement the Singleton pattern in your code?
sobes.tech AI
Answer from AI
The Singleton pattern guarantees that a class has only one instance and provides a global point of access to it. In C++, one common way to implement this is by using a static method with a local static object, which ensures lazy initialization and thread safety starting from C++11:
class Singleton {
public:
static Singleton& getInstance() {
static Singleton instance; // created on first call
return instance;
}
// delete copy and assignment
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
private:
Singleton() {} // private constructor
};
// Usage:
// Singleton& s = Singleton::getInstance();
This approach is simple and effective, requires no additional synchronization, and guarantees the uniqueness of the object.