Qt提供了专门的宏Q_GLOBAL_STATIC,用来实现线程安全的单例模式

*爱你&永不变心* 提交于 2020-04-18 17:31:50

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)

rule.h

#ifndef RULE_H
#define RULE_H

class Rule
{
public:
    static Rule* instance();
};

#endif // RULE_H

rule.cpp

#include "rule.h"

Q_GLOBAL_STATIC(Rule, rule)

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

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

就可以 Rule::instance()->xxxxxx()

 

---

参考文献

https://www.cnblogs.com/findumars/p/10392770.html

http://qtdebug.com/qtbook-singleton/

 

引申阅读

https://doc.qt.io/qt-5/qthreadpool.html Qt线程池

https://doc.qt.io/qt-5/qsharedpointer.html Qt 智能指针

https://doc.qt.io/QtMQTT/index.html Qt Mqtt

 

 

发布了513 篇原创文章 · 获赞 632 · 访问量 349万+
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!