Singleton vs Static Variables

Viewed 108

I am asking because I am curious while studying the singletone pattern.

I want to know the difference between singletone pattern and static variable.

class A
{
public:
    A() {}
    ~A() {}
};

static A* a;

This

class Singleton
{
private:
    Singleton() {}
    ~Singleton() {}
private:
    static Singleton* m_Singleton;
    
public:
    static Singleton* GetInstance()
    {
        if (m_Singleton == nullptr)
        {
            m_Singleton = new Singleton();
        }
        return m_Singleton;
    }
    static void DestroyInstance()
    {
        if (m_Singleton == nullptr)
        {
            return;
        }
        delete m_Singleton;
        m_Singleton = nullptr;
    }
};

Singleton* Singleton::m_Singleton = nullptr;

I want to know the difference between this. Aren't you creating an object using only one? Or I wonder if there's any difference.

2 Answers

The difference is that the user (the programmer that use your class) can create as many instances of A as he/she wants. The porpouse of the singleton design pattern is to be sure to have just one instance of singleton class (Singleton in your case) in the whole program. This is possible declaring the constructor private and then delegate to a static function the duty to return an instance of the class.

If you refere to a sinlgleton in combination with static you potentially want a setup the static version because it is thread save since C++ 11.

class A
{
public:
    A() {}
    ~A() {}
};

A* getInstanceOfA() 
{
    static A a; // Thread save magic static implementing singleton
    return &a;
}

A* globalSingleton = nullptr;

A* getInstanceOfAWithNew() 
{
    if(nullptr == globalSingleton) {
        globalSingleton = new A(); // Not thread save. Would need mutex.
    }
    return globalSingleton;
}

The C++ 11 standard guarantees these kind of static variables to be thread safe. The compiler will make sure the static variable a is initialized only once. This isn't given if you use new A. You need to use some guard.

See How to implement multithread safe singleton in C++11 without using

Related