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()
标签:Singleton,Qt,tptr,举例,static,单例,include,template 来源: https://www.cnblogs.com/AlexSun-2021/p/16458645.html