Next Previous Contents

3. Miscellaneous tools

3.1 Singleton

Definition

A singleton is an application data which is created and deleted only once at the end of the application process. The C++ compiler allows the user to create a static singleton data before the first executable statement. They are deleted after the last statement execution.

The SINGLETON_ template class deals with dynamic singleton. It is useful for functor objects. For example, an object that connects the application to a system at creation and disconnects the application at deletion.

Usage

To create a single instance a POINT object :

# include "Utils_SINGLETON.hxx"
... 
POINT *ptrPoint=SINGLETON_<POINT>::Instance() ; 
assert(ptrPoint!=NULL) ;

No need to delete ptrPoint. Deletion is achieved automatically at exit. If the user tries to create more than one singleton by using the class method SINGLETON_<TYPE>::Instance(), the pointer is returned with the same value even if this is done in different functions (threads ?).

POINT *p1=SINGLETON_<POINT>::Instance() ;
... 
POINT *p2=SINGLETON_<POINT>::Instance() ; 
assert(p1==p2)

Design description

Here are the principles features of the singleton design :


Next Previous Contents