Thers are 2 types of C++ singleton template implementation. One is static singlteon, and the other is global singleton.



[VSingleton template] - static lazy initialization


// ----------------------------------------------------------------------------
// VSingleton (static lazy initialization)
// ----------------------------------------------------------------------------
template <class T>
class VSingleton : private T, VNonCopyable
{
public:
  inline static T& instance()
  {
    static VSingleton<T> s_instance; // declared as static
    return s_instance;
  }
};


VMyInt& myInt = VSingleton<VMyInt>::instance();


Static singleton object is initialized when the object is accessed for the first time in runtime.



[VGSingleton template] - global non-lazy initialization


// ----------------------------------------------------------------------------
// VGSingleton (global non-lazy initialization)
// ----------------------------------------------------------------------------
template <class T>
class VGSingleton : VNonCopyable
{
protected:
  static T g_instance;
public:
  inline static T& instance() { return g_instance; }
};
template <class T> T VGSingleton<T>::g_instance; // declared as global


VMyInt& myInt = VGSingleton<VMyInt>::instance();


Global singleton object is initialized when application starts before entering main entry point.



Both(static singleton and global singleton) objects are deleted when application is to be closed.



[Result]


[static_singleton_test]

main beg

foo1 beg

012FB1C8 VMyInt::VMyInt() // VSingletone object is created when first accessed.

012FB1C8 VMyInt::toInt(0)

myInt=0

012FB1C8 VMyInt(0)::= (int 1)

foo1 end

foo2 beg

012FB1C8 VMyInt::toInt(1)

myInt=1

012FB1C8 VMyInt(1)::= (int 2)

foo2 end

main end

012FB1C8 VMyInt::~VMyInt() 2 // deleted after main function


[global_singleton_test]

0032A188 VMyInt::VMyInt() // VGSingletone object is created when application starts before main entry point.

main beg

foo1 beg

0032A188 VMyInt::toInt(0)

myInt=0

0032A188 VMyInt(0)::= (int 1)

foo1 end

foo2 beg

0032A188 VMyInt::toInt(1)

myInt=1

0032A188 VMyInt(1)::= (int 2)

foo2 end

main end

0032A188 VMyInt::~VMyInt() 2 // deleted after main function



[Download]


singleton_test.zip