COMPASSi/trunk/code/inc/Util/include/Singleton.h

72 lines
2.8 KiB
C
Raw Permalink Normal View History

2025-06-25 15:06:42 +08:00
#ifndef SINGLETON_H
#define SINGLETON_H
#include <QScopedPointer>
/**
* 使:
* 1. (使 SINGLETON):
* class HelloWorld {
* SINGLETON(HelloWorld)
* public:
*
* 2. cpp ( SINGLETON private )
*
* 3. : HelloWorld::instance()->method()
*
* :
* 1. 线
* 2. Qt QSettings QSqlDatabase
* main 退 main qApp
* main
* : qApp aboutToQuit
*/
template <typename T>
class Singleton {
public:
static T* get_instance() {
if (s_instance.isNull()) {
s_instance.reset(new T()); // 此指针会在全局变量作用域结束时自动 deleted (main 函数返回后)
}
return s_instance.data();
}
static void destroy_instance() {
s_instance.reset(nullptr);
}
Singleton(const Singleton& other) = delete;
Singleton<T>& operator=(const Singleton& other) = delete;
private:
static QScopedPointer<T> s_instance;
};
template <typename T> QScopedPointer<T> Singleton<T>::s_instance;
/*-----------------------------------------------------------------------------|
| Singleton Macro |
|----------------------------------------------------------------------------*/
#define SINGLETON(Class) \
private: \
Class(); \
~Class(); \
Class(const Class &other) = delete; \
Class& operator=(const Class &other) = delete; \
friend class Singleton<Class>; \
friend struct QScopedPointerDeleter<Class>; \
\
public: \
static Class* instance() { \
return Singleton<Class>::get_instance(); \
} \
\
static void destroy_instance() { \
Singleton<Class>::destroy_instance(); \
}
#endif // SINGLETON_H