Using the RWTSingleton Class
Singletons ensure that a class has only one instance and provide a global point of access to it. The Threads Module 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 Module solves the problem of deleting singleton instances by using an WTCountingPointer 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.
Example 60 – Creating a singleton instance of an existing class
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.