Qt 中用Q_GLOBAL_STATIC來實現執行緒安全的單例模式

钰清山人發表於2024-05-14
  1. 官方說明:
    Qt中有個宏Q_GLOBAL_STATIC 可以用來建立一個全域性靜態變數,下面看下官方文件的說明:

Q_GLOBAL_STATIC(Type, VariableName)
Creates a global and static object of type QGlobalStatic, of name VariableName and that behaves as a pointer to Type. The object created by Q_GLOBAL_STATIC initializes itself on the first use, which means that it will not increase the application or the library's load time. Additionally, the object is initialized in a thread-safe manner on all platforms.
The typical use of this macro is as follows, in a global context (that is, outside of any function bodies):

Q_GLOBAL_STATIC(MyType, staticType)

官方文件說的意思是:
建立名為VariableName的QGlobalStatic型別的全域性和靜態物件,其行為類似於指向Type的指標。由Q_GLOBAL_STATIC建立的物件在第一次使用時對自身進行初始化,這意味著它不會增加應用程式或庫的載入時間。此外,該物件在所有平臺上都以執行緒安全的方式進行初始化。

  1. 使用方法:
    官方的說明中就已經說了使用方法 :Q_GLOBAL_STATIC(MyType, staticType)

  2. 例項說明:
    singleton.h

#ifndef SINGLETON_H
#define SINGLETON_H
#include <QGlobalStatic>

#define SINGLETON Singleton::instance()

class Singleton
{
public:
    Singleton() {}
    virtual ~Singleton() {}
public:
    static Singleton* instance();
public:
    void setValue(int value);
    int getValue();
prive:
    int m_value;
};
#endif // SINGLETON_H

singleton.cpp

#include "singleton.h"
Q_GLOBAL_STATIC(Singleton, theSingleton)
Rule* Singleton::instance()
{
    return theSingleton();
}

void Singleton::setValue(int value)
{
    m_value = value);
}

int Singleton::getValue()
{
    return m_value;
}

呼叫方法:
如上面的單例在需要呼叫的地方可以用如下方法來賦值和取值:

Singleton::instance()->setValue(520);
int value = Singleton::instance()->getValue();

也可以直接用定義的宏來呼叫

SINGLETON->setValue(520);
int value = SINGLETON->getValue();

相關文章