Singleton implementation

Simon Hausmann hausmann at
Wed Jul 9 09:42:28 BST 2003

On Wed, Jul 09, 2003 at 01:11:40AM -0400, Zack Rusin wrote:
> 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 :
> YourClassSingle::Instance()->someFunc();
> And that's it, you have a complete implementation of a singleton for 
> your class.
> The implementation with a sample test is here :
> Comments?

As much as I'd like to see a good re-usable template for singletons
(I was excited, too, about putting this into kdelibs, when I read
the book :) as much I'm afraid it's of very limited use for us. The
way the destruction is designed with atexit prevents the use of the
template in a library. Apart from very interesting points made by
Havoc on the use of atexit in libraries --
-- there is another problem: Noone calls the function you registered
with atexit when dlclosing the library the function is in.

Another point is that if you put the typedef in your publically
installed header file in a library noone can guarantee that all
methods and static variables (thinking of mpInstance and instance()
itself) are emitted next to the actual class implementation
(YourClass) , which however is necessary for proper function (like
for example if you use static objects instead of atexit for
destruction) .


More information about the kde-core-devel mailing list