zhuzichu520 / FluentUI

FluentUI for QML
MIT License
3.48k stars 456 forks source link

单例的代码里是不是有些问题.. #384

Closed EveryOrigin closed 9 months ago

EveryOrigin commented 9 months ago
#ifndef SINGLETON_H
#define SINGLETON_H

#include <QMutex>
#include <QScopedPointer>
#include <memory>
#include <mutex>

template <typename T>
class Singleton {
public:
    static T* getInstance();

    Singleton(const Singleton& other) = delete;
    Singleton<T>& operator=(const Singleton& other) = delete;

private:
    static std::mutex mutex;
    static T* instance;
};

template <typename T>
std::mutex Singleton<T>::mutex;
template <typename T>
T* Singleton<T>::instance;
template <typename T>
T* Singleton<T>::getInstance() {
    if (instance == nullptr) {
        std::lock_guard<std::mutex> locker(mutex);
        if (instance == nullptr) {
            instance = new T();
        }
    }
    return instance;
}

#define SINGLETONG(Class)                              \
private:                                               \
    friend class Singleton<Class>;              \
    friend struct QScopedPointerDeleter<Class>;        \
                                                       \
    public:                                                \
    static Class* getInstance() {                      \
        return Singleton<Class>::getInstance(); \
}

#endif // SINGLETON_H

好像作者是想使用QScopedPointer 但是instance类型直接写了个T* ....

或许可以改成这样

#ifndef SINGLETON_H
#define SINGLETON_H

#include <QMutex>
#include <QScopedPointer>

template <typename T>
class Singleton {
public:
    static T* getInstance();

    Singleton(const Singleton& other) = delete;
    Singleton<T>& operator=(const Singleton& other) = delete;

private:
    static QMutex mutex;
    static QScopedPointer<T> instance;
};

template <typename T>
QMutex Singleton<T>::mutex;
template <typename T>
QScopedPointer<T> Singleton<T>::instance;
template <typename T>
T* Singleton<T>::getInstance() {
    if (instance.isNull()) {
        QMutexLocker locker(&mutex);
        if (instance.isNull()) {
            instance.reset(new T());
        }
    }
    return instance.take();
}

#endif // SINGLETON_H
suterberg commented 9 months ago

改了之后可以运行么?

EveryOrigin commented 9 months ago

改了之后可以运行么?

上次试了好像是可以 最近没怎么搞 在折腾pyside