Qt代码举例-单例模式

使用Qt方便的实现单例模式

单例类的实现,其中qCallOnce函数是确保该函数只执行一次:

复制代码
#ifndef SINGLETON
#define SINGLETON

#include <QtGlobal>
#include <QScopedPointer>
#include "call_once.h"

template <class T>
class Singleton
{
public:
    static T& instance()
    {
        qCallOnce(init, flag);
        return *tptr;
    }

    static void init()
    {
        tptr.reset(new T);
    }

private:
    Singleton() {}
    ~Singleton() {}
    Q_DISABLE_COPY(Singleton)

    static QScopedPointer<T> tptr;
    static QBasicAtomicInt flag;
};

template<class T> QScopedPointer<T> Singleton<T>::tptr(0);
template<class T> QBasicAtomicInt Singleton<T>::flag = Q_BASIC_ATOMIC_INITIALIZER(CallOnce::CO_Request);

#endif // SINGLETON
复制代码

使用举例:

1 class TestClass : public QObject
2 {
3 };
4 #define TestClassInstance Singleton<TestClass >::instance()

 还有一种更简单的:

复制代码
#include <QMutexLocker>

class TestClass
{
public:
    inline static TestClass* nstance()
    {
        QMutexLocker locker(&mutex);
        if (NULL == m_instance)
        {
            m_instance = new TestClass();
        }
        return m_instance;
    }
    
private:
    static QMutex mutex;
    static TestClass* m_instance;
};
复制代码

 

posted @   AlexSun_2021  阅读(533)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
点击右上角即可分享
微信分享提示