2026-08-14 03:10:49 +02:00
2022-10-18 14:02:19 +02:00
2022-10-18 14:02:19 +02:00
2026-08-14 03:10:49 +02:00

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> template
  • qtsingleton/callonce.h - qCallOnce and per thread variant
  • CMakeLists.txt - install headers to include/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+

S
Description
Qt-based singleton object
Readme
37 KiB
0 Stars 1 Watchers 0 Forks
Languages
C++ 92.3%
CMake 7.7%