Qt单例:Qt有专门的宏Q_GLOBAL_STATIC,用来实现线程安全的单例模式

415 阅读1分钟

Qt本身就提供了专门的宏 Q_GLOBAL_STATIC。通过这个宏不但定义简单,还可以获得线程安全性。

1、先看官方文档

doc.qt.io/qt-5/qgloba…

doc.qt.io/qt-5/thread…

 

2、再看使用方法

Q_GLOBAL_STATIC(Type, VariableName)
Q_GLOBAL_STATIC_WITH_ARGS(Type, VariableName, Arguments)

 

3、举例说明

rule.h

#ifndef RULE_H
#define RULE_H

#include <QGlobalStatic>
#define RULE Rule::instance()

class Rule
{
public:
    Rule() {}
    virtual ~Rule() {}

public:
    static Rule* instance();

public:
    void test();
};

#endif // RULE_H

rule.cpp

#include "rule.h"

Q_GLOBAL_STATIC(Rule, rule)

Rule* Rule::instance()
{
    return rule();
}

void Rule::test()
{
    //todo
}

在任何地方,引用头文件 include "rule.h"

就可以Rule::instance()->test();

或者使用宏RULE->test();

 

---

参考文献

www.cnblogs.com/findumars/p…

qtdebug.com/qtbook-sing…

 

引申阅读

doc.qt.io/qt-5/qthrea… Qt线程池

doc.qt.io/qt-5/qshare… Qt 智能指针

doc.qt.io/QtMQTT/inde… Qt Mqtt

wiki.qt.io/QtDesignStu…