From e90ad159371e1f83e02ae10db326c2b2fbffdfbd Mon Sep 17 00:00:00 2001 From: Christian Gmeiner Date: Tue, 2 Jun 2009 08:30:13 +0200 Subject: rework singleton class --- dxr3singleton.h | 47 ++++++++++++++++++++++++++++++----------------- 1 file changed, 30 insertions(+), 17 deletions(-) (limited to 'dxr3singleton.h') diff --git a/dxr3singleton.h b/dxr3singleton.h index ebfbe42..b53ac79 100644 --- a/dxr3singleton.h +++ b/dxr3singleton.h @@ -1,7 +1,7 @@ /* * dxr3singleton.h * - * Copyright (C) 2004 Christian Gmeiner + * Copyright (C) 2004-2009 Christian Gmeiner * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License @@ -22,30 +22,43 @@ #ifndef _DXR3_SINGLETON_H_ #define _DXR3_SINGLETON_H_ -// ================================== -//! A singleton template. -/*! - Is a nice solution to use only - one instance of a class. -*/ +#include +#include + template -class Singleton { +class Singleton +{ public: - virtual ~Singleton() {} - static T& Instance(); + static T *instance() { + + // use double-checked looking + // see http://en.wikipedia.org/wiki/Double-checked_locking + if (inst.get() == 0) { + m.Lock(); + if (inst.get() == 0) { + inst = std::auto_ptr(new T); + } + m.Unlock(); + } + + return inst.get(); + } + + virtual ~Singleton() { }; protected: - Singleton() {} + Singleton() { } private: - Singleton(const Singleton&); + static std::auto_ptr inst; + static cMutex m; }; -template -T& Singleton::Instance() { - static T instance; - return instance; -} +template +std::auto_ptr Singleton::inst(0); + +template +cMutex Singleton::m; #endif /*_DXR3_SINGLETON_H_*/ -- cgit v1.2.3