Chapter 14. Singleton objects

x::singleton implements support for classes that always have only a single class instance during the application's lifetime:

#include <x/singleton.H>

class myClassObj : virtual public x::obj {

// class definition

};

typedef x::ref<myClassObj> myClass;

x::singleton<myClassObj> myClassInstance;

// ...

myClass c(myClassInstance.get());

c->method();

The object gets constructed the first time get() gets invoked. Subsequent calls to get() returns a reference to the same object.

The parameter to the template class must be a reference-counted object that has a default constructor. An instance of the singleton template class can only be declared in the static scope, and may not be declared on the stack.

Note

get() may not be invoked from constructors or destructors of other classes. Constructors and destructors can get called when a thread or an application is in the middle of initializing or terminating, and the underlying support for singleton objects is not available.