Rogue Wave banner
Previous fileTop of DocumentContentsIndexNext file

7.4 Using the RWTSingleton Class

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.

Example 63 -- Creating a singleton instance of an existing class

To create a singleton instance of class Foo you write:

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:


NOTE: The RWTCountingPointer operator->() may not be available on all platforms. For maximum portability, use operator*() as in the second example above.

Previous fileTop of DocumentContentsIndexNext file

©Copyright 2000, Rogue Wave Software, Inc.
Contact Rogue Wave about documentation or support issues.