STL Singleton Template

Singleton is one of my favorite design pattern, I use it to keep a global information for my application such as Configurations, Logger etc. I remember I wrote a post regarding simple singleton class, which it does not really work as singleton. It is just a silly way to make a object class looks like singleton.

Lately I’ll been using STL Singleton template for my projects, I find it simple to implement and yet efficient.

Lets define the Singleton Template:

template<typename T>

class CSingleton
{
    public:
        static T& Instance()
        {
            static T me;
            return me;
        }
};

In order to turn your own class into singleton, you class must inherits from CSingleton like this:

class MyClass: public CSingleton<MyClass>
{
    public:
        MyClass(){};
        ~MyClass(){};
        void Print() { printf("testing %d\n",val); }
        int val;
};

Access MyClass variables and functions like this:

int main(void)
{
   MyClass::Instance().val=7;
   MyClass::Instance().Print();
   
   return 0;
}

I find the appearance of MyClass::Instance() are ugyl and lengthy, therefore I like to define a nicer look of singleton class.

#define MYCLASS MyClass::Instance()

So my source code looks cleaner.

int main(void)
{
   MYCLASS.val=7;
   MYCLASS.Print();
   
   return 0;
}

Anyway, this is just my preference. Enjoy yourself with STL Singleton Template.

4 thoughts on “STL Singleton Template

  1. I am guessing this is not a perfect singleton class.

    As We can still do MyClass _myClass = new MyClass();

    For a class to be singleton, we should make the constructor private. So that we can construct with a createInstance method.

    That way, only one instance of class MyClass will be there in the app always.

    0.02,
    Kartik

  2. Pingback: » STL Singleton Template A C One: What The World Is Saying About A C One

  3. Singleton can be implemented in another way as well. We shall declare a static variable in the class. Then in the constructor(which can be public), we will increment the static variable(which is our object instance). If we see the object count exceeding 1, then we can throw from the constructor. By this you can always new for only once from anywhere it is used, and it serves the rule of singleton.

  4. Yeah, this doesn’t implement the pattern at all and has nothing to do with STL other than it uses a template and STL uses templates. A templated singleton implies I can’t construct another object of the type simply by inheriting from that class. All this does is give you a factory instance method. This is a great way to legitimize your global variable with a design pattern and reduce your code into a dependency mess. That this trainwreck shows up in a google top five shows you how little the industry understands design patterns and C++.

Leave a Reply

Your email address will not be published. Required fields are marked *