Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is my singleton template really a singleton?

I was told that my singleton template may not truly be a singleton, in that there is ways to create more than one object with it. When I asked how to fix it, I was ignored. That is why I come here to ask is my singleton template class truly a singleton?

#ifndef SINGLETON_H_
#define SINGLETON_H_

template <class T>
class Singleton
{
private:
static T* instance;

protected:
    Singleton<T>(  )
    {
    }

public:
    static T* getInstancePtr(  )
    {
        if ( instance == 0 )
            instance = new T(  );

        return instance;
    }
};

template <class T> T* Singleton<T>::instance = 0;

#endif

This is then inherited by a class which I wish to be a singleton like so:-

class Console : public Singleton< Console >
{
};
like image 726
ctor Avatar asked Nov 30 '25 04:11

ctor


1 Answers

You've made the default constructor protected. The derived class can access it, so this will compile:

Console c1, c2;
like image 142
jrok Avatar answered Dec 01 '25 17:12

jrok



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!