Singletons ensure that a class has only one instance and provide a global point of access to it. The Threads.h++ singleton implementation is the RWTSingleton class. Because RWTSingleton is a template class, it can adapt existing classes to behave as singletons, as shown in the example below.
Threads.h++ solves the problem of deleting singleton instances by using an RWTCountingPointer smart pointer in the RWTSingleton<T> interface. You can think of RWTCountingPointer as a handle to the singleton instance. When no more handles are bound to the singleton instance and the program terminates, the singleton instance dies.
In the following example, suppose you want to create a singleton version of your existing class Foo.
class Foo { public: void function(); };
To create a singleton instance of class Foo you write:
RWTCountingPointer<Foo> singleFooPtr = RWTSingleton<Foo>::instance();
The first call to instance() creates a Foo instance on the heap, by calling Foo's default constructor, and returns it. The returned singleton is wrapped in an RWTCountingPointer. Now you can use either of the RWTCountingPointer dereferencing operations to call function(). For example:
singleFooPtr->function(); or (*singleFooPtr).function();
NOTE: The RWTCountingPointer operator->() may not be available on all platforms. For maximum portability, use operator*() as in the second example above.
©Copyright 2000, Rogue Wave Software, Inc.
Contact Rogue Wave about documentation or support issues.