Singleton implementation

Zack Rusin zack at
Wed Jul 9 06:11:40 BST 2003


I had this on the drive for quite a while - it's a singleton 
implementation heavily based on the one from "Modern C++ Design". 
Someone reminded me of it and I decided to see what people think about 
For those who haven't read "Modern C++ Design" - the singleton 
implementation from that book is template-policy based. Meaning 
template classes define its behavior. The basic class is the 
KDE::SingletonHolder. It's a three argument template class with the 
following arguments : 
        typename T,
        template <class> class CreationPolicy = CreateUsingNew,
        template <class> class LifetimePolicy = DefaultLifetime
    class SingletonHolder { ... };

The typename T is, of course, the class which one wants to use as a 
singleton. The CreationPolicy is a way in which one wants to 
create/destroy the singleton. Currently there are three policies (and I 
don't think we can have more of those) :
- CreateUsingNew - creates/destroys with the new/delete pair,
- CreateUsingMalloc - malloc/free respectively,
- CreateStatic - creates the object in static memory.
LifetimePolicy defines how/when should the singleton be destructed. 
There are four policies for those:
-  DefaultLifetime - simply schedules the CreationPolicy destruction 
with the std::atexit function,
- KDEDefaultLifetime - similar to DefaultLifetime but uses 
KStaticDeleterBase & KGlobal functions dealing with KStaticDeleterBase 
to perform destruction,
- PhoenixSingleton - like DefaultLifetime but allows recreation of a 
destructed singleton and its another destruction (useful when a 
singleton on which a few others singletons depends on is deleted before 
those singletons),
- SingletonWithLongevity - it's a nice implementation of that policy 
that lets the user decide in which order the singletons using this 
policy will be deleted.
So, how does one use all that  to get a singleton?
You write your class just like it would be a normal class. Then in your 
header you add:
#include <ksingleton.h>
typedef KDE::SingletonHolder< YourClass > YourClassSingle;
Now YourClassSingle::Instance() returns a pointer to the singleton of 
YourClass, so you use it like :
And that's it, you have a complete implementation of a singleton for 
your class.

The implementation with a sample test is here :


"Daddy, what does "C: Format Complete" mean? "
"It means you're dead"

More information about the kde-core-devel mailing list