#include <QtCore/QAtomicPointer>
#include <QtCore/QHash>
Go to the source code of this file.
Namespaces | |
namespace | Log4Qt |
Classes | |
class | Log4Qt::InitialisationHelper |
The class InitialisationHelper performs static initialisation tasks. More... | |
Defines | |
#define | LOG4QT_GLOBAL_STATIC(TYPE, FUNCTION) |
#define | LOG4QT_IMPLEMENT_INSTANCE(TYPE) |
#define LOG4QT_GLOBAL_STATIC | ( | TYPE, | |||
FUNCTION | ) |
Value:
static QBasicAtomicPointer<TYPE > sp_global_static_##FUNCTION = \ Q_BASIC_ATOMIC_INITIALIZER(0); \ TYPE *FUNCTION() \ { \ if (!sp_global_static_##FUNCTION) \ { \ TYPE *p_temp = new TYPE; \ if (!sp_global_static_##FUNCTION.testAndSetOrdered(0, \ p_temp)) \ delete p_temp; \ } \ return sp_global_static_##FUNCTION; \ }
The macro uses a static variable to store a pointer to the singleton object. On the first invocation an object of the type TYPE is created on the heap and the pointer is set. Any further invocations will return the stored pointer. If multiple threads are accessing the function without the pointer being set, each thread will create an object of the type TYPE. The threads that find the pointer already been set will delete their object. The singleton object will not be deleted during static de-initialisation.
The following example uses a global global mutex object to synchronise access to a static member variable.
#file: myclass.h class MyClass { public: MyClass(); ~MyClass(); private: static qint64 msObjectCount; }
#file: myclass.cpp #include myclass.h LOG4QT_GLOBAL_STATIC(QMutex, class_guard) MyClass::MyClass() { QMutexLocker(class_guard()); msObjectCount++; } MyClass::~MyClass() { QMutexLocker(class_guard()); msObjectCount--; } qint64 MyClass::msObjectCount = 0;
#define LOG4QT_IMPLEMENT_INSTANCE | ( | TYPE | ) |
Value:
static QBasicAtomicPointer<TYPE > sp_singleton_##TYPE = \ Q_BASIC_ATOMIC_INITIALIZER(0); \ TYPE *TYPE::instance() \ { \ if (!sp_singleton_##TYPE) \ { \ TYPE *p_temp = new TYPE; \ if (!sp_singleton_##TYPE.testAndSetOrdered(0, p_temp)) \ delete p_temp; \ } \ return sp_singleton_##TYPE; \ }
The function works like the one created by LOG4QT_GLOBAL_STATIC.
The following example illustrates how to use the macro to create a singleton class:
#file: mysingleton.h class MySingleton { private: MySingleton(); ~MySingleton(); public: MySingleton *instance(); }
#file: mysingleton.cpp #include mysingleton.h MySingleton::MySingleton() {} MySingleton::~MySingleton() {} LOG4QT_IMPLEMENT_INSTANCE(MySingleton)