Skip to content

Commit 049c570

Browse files
committed
Add a Singleton that correctly allows usage from several dlls
1 parent fd7e8c9 commit 049c570

File tree

3 files changed

+24
-13
lines changed

3 files changed

+24
-13
lines changed

qrutils/imagesCache.h

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,9 @@ namespace utils {
2828
/// Pixmaps and svg images are contained separately as they are rendered differently.
2929
class QRUTILS_EXPORT ImagesCache: public utils::Singleton<ImagesCache>
3030
{
31+
Q_OBJECT
3132
public:
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.

qrutils/qrutils.pri

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff 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

5859
FORMS += \
5960
$$PWD/watchListWindow.ui

qrutils/singleton.h

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -14,29 +14,38 @@
1414

1515
#include <QMutex>
1616
#include <QSharedPointer>
17-
1817
#pragma once
1918

2019
namespace 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.
2341
template<typename T>
24-
class Singleton
42+
class Singleton: public QObject
2543
{
2644
public:
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

0 commit comments

Comments
 (0)