File tree Expand file tree Collapse file tree 3 files changed +24
-13
lines changed
Expand file tree Collapse file tree 3 files changed +24
-13
lines changed Original file line number Diff line number Diff line change @@ -28,8 +28,9 @@ namespace utils {
2828// / Pixmaps and svg images are contained separately as they are rendered differently.
2929class QRUTILS_EXPORT ImagesCache: public utils::Singleton<ImagesCache>
3030{
31+ Q_OBJECT
3132public:
32- ~ImagesCache () = default ;
33+ ~ImagesCache () override {} ;
3334
3435 // / Draws image with given file name with a given painter in given rectangle. Note that actual file, from which
3536 // / an image will be loaded may be different from fileName, as described in selectBestImageFile.
Original file line number Diff line number Diff line change @@ -54,6 +54,7 @@ SOURCES += \
5454 $$PWD /generator/abstractGenerator.cpp \
5555 $$PWD /widgetFinder.cpp \
5656 $$PWD /imagesCache.cpp \
57+ $$PWD /singleton.cpp \
5758
5859FORMS += \
5960 $$PWD /watchListWindow.ui
Original file line number Diff line number Diff line change 1414
1515#include < QMutex>
1616#include < QSharedPointer>
17-
1817#pragma once
1918
2019namespace utils {
2120
21+ class SingletonImpl
22+ {
23+ public:
24+ template <typename T> static QSharedPointer<T> instance (const std::function<T*()>& factory) {
25+ QMutexLocker lock (&_m);
26+ auto &instance = _typeToObject[&T::staticMetaObject];
27+ if (auto result = instance.lock ()) {
28+ return qWeakPointerCast<T, QObject>(result);
29+ }
30+ auto result = QSharedPointer<T>(factory ());
31+ _typeToObject[&T::staticMetaObject] = qSharedPointerCast<QObject, T>(result);
32+ return result;
33+ }
34+ private:
35+ static QHash<const void *, QWeakPointer<QObject>> _typeToObject;
36+ static QMutex _m;
37+ };
38+
39+
2240// / Instantiates and provides to all callers single instance of the some type.
2341template <typename T>
24- class Singleton
42+ class Singleton : public QObject
2543{
2644public:
2745 // / Creates single instance of some type (given in class template) if it does not exist and returns it.
2846 static QSharedPointer<T> instance ()
2947 {
30- static QMutex m;
31- QMutexLocker lock (&m);
32- static QWeakPointer<T> instance;
33- if (auto result = instance.lock ()) {
34- return result;
35- } else {
36- result = QSharedPointer<T>(new T ());
37- instance = result;
38- return result;
39- }
48+ return SingletonImpl::instance<T>([]() -> T* {return new T ();});
4049 }
4150};
4251
You can’t perform that action at this time.
0 commit comments