The Norse God and C++ Singleton

In Norse Mythology Loki was considered as a God of Giants along with other powers it had the power to shift shapes and bodies , though my interest in this topic is flimsy, however while skimming through the book  Modern C++ Design , I realized that the author Andrei Alexandrescu named a well written library after this thing anyways the aim of this post is just to show you how a simple singleton is usually achieved and how it can be achieved by using the LOKI library.You can find more information about LOKI here.


Simple Singleton Without Loki
class MyClass
{
 static MyClass* Class_Address;
 public:
  int a;
    static MyClass * GetInstance()
    {
      if (Class_Address==NULL)
      {
      Class_Address = new MyClass;
      return Class_Address;
      }
      else
      {
      return Class_Address;
      }
    }
 private:
    ~MyClass(){}
};
MyClass* MyClass::Class_Address = NULL;

void main()
{
MyClass *an_inst;
an_inst = MyClass::GetInstance();
an_inst->a=12;

MyClass *an_inst2;
an_inst2 = MyClass::GetInstance();
cout << an_inst2->a; //output would be 12
}

Simple Singleton With Loki 
#include <iostream>
#include <loki/Singleton.h>  
using namespace Loki;
class MyClass
{
public:
   int a;
};

typedef SingletonHolder<MyClass,CreateUsingNew,PhoenixSingleton> myinstance;

int main()
{
    myinstance::Instance().a = 12;
    MyClass Instance2 = myinstance::Instance();
    std::cout << Instance2.a; //output is 12
    std::cin.get();
}
There are tons of ways creating a singleton without using LOKI however  the aim of this post was to introduce the LOKI library.In case you have any questions or you simply enjoyed  reading the article please leave your comments here.

No comments:

Post a Comment