TITLE: Singleton idiom example AUTHOR: kanze@lts.sel.alcatel.de (James Kanze), 6 Sep 95 I believe that the standard idiom for this is to use a (function) local variable, rather than one on the heap, for the singleton. My own (typical) solution is generally along the lines of: class SingletonAccessor { public : SingletonAccessor() ; Singleton const* operator->() const ; Singleton* operator->() ; private : static Singleton* impl ; static Singleton* initialize() ; } ; inline SingletonAccessor::SingletonAccessor() { if ( impl == NULL ) impl = initialize() ; } inline Singleton const* SingletonAccessor::operator->() const { return impl ; } inline Singleton* SingletonAccessor::operator-> { return impl ; } Singleton* SingletonAccessor::initialize() { static Singleton theOneObject ; return &theOneObject ; } [ Note here that the design uses a static object. This means that the singleton will not be created until initialize() is called. It also means that it will be destroyed when the program exits, a weakness in SES's singleton idiom. -adc ] In Singleton, the constructor/destructor are private, and SingletonAccessor is a friend class. Notes: 1. In order to access Singleton, it is necessary for an instance of SingletonAccess to exist. This guarantees that the Singleton has been correctly constructed before use. 2. In many cases, rather than provide operator-> and make the structure of Singleton visible, I will define the complete interface in SingletonAccessor. This reduces compilation dependencies, at a very small run-time cost. 3. An alternative to 2 is to declare Singleton as an abstract class, with no data and only the publicly accessible functions, all pure virtual. In the module which implements SingletonAccess::initialize, declare SingletonImpl, derived from Singleton, with all of the works. SingletonAccessor then has a local instance of SingletonImpl (rather than a Singleton). 4. The Singleton cannot be used in the destructors of static objects. In theory, if the order of destruction is the opposite of construction, it could be, at least in some carefully crafted cases. In practice, however, most compilers do not maintain this ordering with local static variables. So we're out of luck.