diff options
Diffstat (limited to 'singleton.h')
| -rw-r--r-- | singleton.h | 44 |
1 files changed, 44 insertions, 0 deletions
diff --git a/singleton.h b/singleton.h new file mode 100644 index 0000000..b170210 --- /dev/null +++ b/singleton.h @@ -0,0 +1,44 @@ +#pragma once + +// qt +#include <QMutex> +#include <QSharedPointer> + +#define SINGLETON(type) Singleton<type>::get().data() + +template <class T> class Singleton +{ +public: + static QSharedPointer<T> get() + { + static QMutex mtx; + QMutexLocker l(&mtx); + + if (!m_instance) + { + m_instance.reset( + static_cast<T*>(T::staticMetaObject.newInstance()) + // FIXME: deleteLater doesn't work. Crashes without it + , + &T::deleteLater + ); + } + + return m_instance; + } + static void cleanup() + { + static QMutex mtx; + QMutexLocker l(&mtx); + + m_instance.clear(); + } + + typedef QSharedPointer<T> FactorySharedPointer; + +private: + static FactorySharedPointer m_instance; +}; + +template <class T> +typename Singleton<T>::FactorySharedPointer Singleton<T>::m_instance; |
