GenericSingelton.h 1.63 KB
Newer Older
1 2 3 4 5
#pragma once
#include "call_once.h"
#include <QScopedPointer>
#include <QtGlobal>

6 7
// from https://stackoverflow.com/questions/46172607/qt-singleton-implementation

8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
template <class T> class GenericSingelton {
private:
  typedef T *(*CreateInstanceFunction)();

public:
  static T *instance(CreateInstanceFunction create);

private:
  static void init();

  GenericSingelton();
  ~GenericSingelton();
  Q_DISABLE_COPY(GenericSingelton)
  static QBasicAtomicPointer<void> create;
  static QBasicAtomicInt flag;
  static QBasicAtomicPointer<void> tptr;
  bool inited;
};

template <class T>
T *GenericSingelton<T>::instance(CreateInstanceFunction create) {
  GenericSingelton::create.store(reinterpret_cast<void *>(create));
  qCallOnce(init, flag);
  return (T *)tptr.load();
}

template <class T> void GenericSingelton<T>::init() {
  static GenericSingelton singleton;
  if (singleton.inited) {
    CreateInstanceFunction createFunction =
        (CreateInstanceFunction)GenericSingelton::create.load();
    tptr.store(createFunction());
  }
}

template <class T> GenericSingelton<T>::GenericSingelton() { inited = true; }

template <class T> GenericSingelton<T>::~GenericSingelton() {
  T *createdTptr = (T *)tptr.fetchAndStoreOrdered(nullptr);
  if (createdTptr) {
    delete createdTptr;
  }
  create.store(nullptr);
}

template <class T>
QBasicAtomicPointer<void>
    GenericSingelton<T>::create = Q_BASIC_ATOMIC_INITIALIZER(nullptr);
template <class T>
QBasicAtomicInt GenericSingelton<T>::flag =
    Q_BASIC_ATOMIC_INITIALIZER(CallOnce::CO_Request);
template <class T>
QBasicAtomicPointer<void>
    GenericSingelton<T>::tptr = Q_BASIC_ATOMIC_INITIALIZER(nullptr);