Friday, February 24, 2023

C++ Singleton Pattern


The singleton pattern is a design pattern that ensures that a class has only one instance, and provides a global point of access to that instance.
the singleton pattern can be implemented using a combination of a private constructor, a static instance variable, and a static method to access the instance.

    class Singleton

    {

    private:

        static Singleton* instance;

        Singleton() {}


    public:

        static Singleton* getInstance()

        {

            if (instance == nullptr)

            {

                instance = new Singleton;

            }

            return instance;

        }

        void doSomething()

        {

            std::cout << "doing something" << std::endl;

        }

    };

    Singleton* Singleton::instance = nullptr;


In this example, the class Singleton has a private constructor and a private static instance variable. The class also has a public static method getInstance() which creates an instance of the class if it doesn't exist and returns a pointer to the instance.

The getInstance() method uses a simple form of lazy initialization to create the instance of the class only when it is first requested. This is known as the Meyers' Singleton.

To use this singleton, we can call the getInstance() method like this:

    Singleton* singleton = Singleton::getInstance();
    singleton->doSomething();

This will output "doing something" in the console.

It is important to note that in this example, the singleton instance is not thread-safe, if you want to use the singleton in a multi-threaded environment, you need to make sure that the singleton's methods are thread-safe and also need to use a technique such as double-checked locking to ensure that multiple threads do not create multiple instances of the singleton.

It's important to note that the singleton pattern is considered an anti-pattern by some developers as it may cause issues with testing, maintainability, and flexibility, and it's better to use dependency injection instead.

This example is a basic example of the singleton pattern in C++, but in a real-world scenario, it's recommended to use a thread-safe implementation and also to handle the lifetime of the singleton properly.


The singleton pattern is a design pattern that ensures that a class has only one instance and provides a global point of access to it. In C++, a thread-safe version of the singleton pattern can be implemented using a combination of a static instance variable, a private constructor, and a double-checked locking mechanism. Here's an example of a thread-safe singleton class in C++:

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

        // Private constructor to prevent instantiation
        Singleton() {}

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

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

In this example, the getInstance() method uses a double-checked locking mechanism to ensure that only one instance of the Singleton class is created, even in a multithreaded environment. The use of the std::mutex and std::unique_lock classes ensure that the instance variable is accessed in a thread-safe manner.

No comments:

Post a Comment

LeetCode C++ Cheat Sheet June

🎯 Core Patterns & Representative Questions 1. Arrays & Hashing Two Sum – hash map → O(n) Contains Duplicate , Product of A...