Proud::CSingleton< T > Class Template Reference

Classes

class  Holder
 

Public Types

typedef RefCount< T > PtrType
 

Static Public Member Functions

static _Noinline PtrType GetSharedPtr ()
 
static T & GetUnsafeRef ()
 

Detailed Description

template<typename T>
class Proud::CSingleton< T >

Singleton template that makes only JIT instancing to be thread safe.

  • Only CS locks JIT instancing process making it thread safe and makes thread unsafe after created.
  • Only thread synchronized then not needed afterwards, e.g. Server down with little frequency can be prevented by using this object at CItemTemplate ans so on.

General usage

  • Creates derivative class to this class. The name of the derivative class is to enter at T.
  • Gets reference of Singleton using Instance(). Object is instanced when Instance() is called for the first time.
  • To control the destruction order of Singletons, constructor of Signleton should approach to dependent target Singleton just for once.

Usage example

class A:public CSingleton<A>
{
public:
void Foo();
};
void Aoo()
{
A::Instance().Foo();
}

If DLL and EXE to use same Singleton,

  • This class must be realized as followings for the case that DLL provides CSingleton and EXE uses it. Otherwise, the singleton used by EXE and the singleton used by DLL will exist as different instance.
    class Goofie:protected CSingleton<Goofie> // Declared as protected to prevent direct access of Instance
    {
    public:
    __declspec(dllexport) Goofie& Instance() // Override CSingleton.Instance() but make it as a function exported from DLL.
    {
    return __super::Instance(); // Returns the instance that is created in DLL module memory space
    }
    };

You can define destruction order of singletons by keeping shared pointer object from singleton.

Example code

// Singleton Class
class MySingleton:public CSingleton<MySingleton>
{
...
Something();
};
// It is the user that has access to Singleton.
class MyGoo
{
// While MyGoo instance exists, it must have this member in order to assure Singleton’s survival.
// Use this member for Singleton access, of course.
MySingleton::PtrType m_mySingleton;
// constructor
User()
{
// It guarantee survival of singleton with increasing singleton refer count.
m_mySingleton = MySingleton::GetInstanceAccessor();
}
Foo()
{
...
// To access singleton, use singleton smartpointer object that already has.
// do not use MySingleton::Instance(), but use this member variable.
m_mySingleton->Something();
}
}