QtSingleton
Header only Qt singleton implementation with thread safe lazy initialization.
The library provides a Singleton<T> template and a qCallOnce helper based on
CallOnce. It is used across the pylatus project for single instance objects such as loggers and factories.
Contents
qtsingleton/singleton.h-Singleton<T>templateqtsingleton/callonce.h-qCallOnceand per thread variantCMakeLists.txt- install headers toinclude/qtsingleton
The library is header only. No compilation is required, only include the headers and link with Qt.
Requirements
- Qt 5.12 or later, Qt 6 supported
- C++11
The implementation uses QBasicAtomicPointer, QBasicAtomicInt, QMutex,
QWaitCondition, QThreadStorage and qCallOnce. For Qt >= 5.14 the relaxed atomic operations are used.
Usage
Define a class with a static instance() method and a factory function:
#include <qtsingleton/singleton.h>
class MyClass {
public:
static MyClass* instance() {
return Singleton<MyClass>::instance(&MyClass::createInstance);
}
static MyClass* createInstance() {
return new MyClass();
}
private:
MyClass() {}
};
Use:
MyClass* obj = MyClass::instance();
The instance is created on first call in a thread safe manner and destroyed on program exit. The destructor deletes the created object and resets atomic state.
Example from the auxygen tree:
auxygen/logger/loggersingleton.cpp:69 shows the pattern used for LoggerSingleton.
Build and install
The CMakeLists installs headers to include/qtsingleton:
cmake -DCMAKE_INSTALL_PREFIX=/usr ...
make install
As a header only library it can also be used by adding the source directory to the include path.
License
GPL-3.0+