Qt本身就提供了专门的宏 Q_GLOBAL_STATIC。通过这个宏不但定义简单,还可以获得线程安全性。
1、先看官方文档
https://doc.qt.io/qt-5/qglobalstatic.html
https://doc.qt.io/qt-5/threads-reentrancy.html
2、再看使用方法
Q_GLOBAL_STATIC(Type, VariableName)
Q_GLOBAL_STATIC_WITH_ARGS(Type, VariableName, Arguments)
3、举例说明
rule.h
1 #ifndef RULE_H
2 #define RULE_H
3 #include <QGlobalStatic>
4 #define RULE Rule::instance()
5 class Rule
6 {
7 public:
8 Rule() {}
9 virtual ~Rule() {}
10 public:
11 static Rule* instance();
12 public:
13 void test();
14 };
15 #endif // RULE_H
rule.cpp
1 #include "rule.h"
2 Q_GLOBAL_STATIC(Rule, rule)
3 Rule* Rule::instance()
4 {
5 return rule();
6 }
7 void Rule::test()
8 {
9 //todo
10 }
在任何地方,引用头文件 include "rule.h"
就可以Rule::instance()->test();
或者使用宏RULE->test();