用 QGlobalStatic 实现 C++ Qt 中的单例模式及其原理解释
单例模式是一种常用的设计模式,保证一个类在整个应用程序中只有一个实例存在,并提供一个全局访问点。在 C++ Qt 中,我们可以使用 QGlobalStatic 类来实现单例模式,其原理如下:
QGlobalStatic 在程序启动时创建一个静态全局变量,而不是在第一次调用该单例对象时创建动态对象。这意味着 QGlobalStatic 对象在使用之前必须被初始化,以便在使用时该对象已经存在并且可以被使用。
以下是一个使用 QGlobalStatic 实现单例模式的示例代码:
#include <QGlobalStatic>
#include <QDebug>
class Singleton {
public:
static Singleton& instance() {
return singletonInstance;
}
void showMessage() {
qDebug() << "Hello, singleton!";
}
private:
Singleton() {}
static Singleton singletonInstance;
friend struct QGlobalStaticDeleter<Singleton>;
};
Q_GLOBAL_STATIC(Singleton,