qt 实现单例
发布日期:2021-10-03 22:59:34 浏览次数:27 分类:技术文章

本文共 1538 字,大约阅读时间需要 5 分钟。

头文件:

class ConnectionManager

{
public:
    static ConnectionManager *instance();

};

实现文件:

Q_GLOBAL_STATIC(ConnectionManager, connectionManager)

ConnectionManager *ConnectionManager::instance()

{
    return connectionManager();
}

 

使用:

ConnectionManager::instance()

 

// POD for Q_GLOBAL_STATIC

template <typename T>
class QGlobalStatic
{
public:
    QBasicAtomicPointer<T> pointer;
    bool destroyed;
};

 

// Created as a function-local static to delete a QGlobalStatic<T>

template <typename T>
class QGlobalStaticDeleter
{
public:
    QGlobalStatic<T> &globalStatic;
    QGlobalStaticDeleter(QGlobalStatic<T> &_globalStatic)
        : globalStatic(_globalStatic)
    { }

    inline ~QGlobalStaticDeleter()

    {
        delete globalStatic.pointer;
        globalStatic.pointer = 0;
        globalStatic.destroyed = true;
    }
};

 

 

#define Q_GLOBAL_STATIC_INIT(TYPE, NAME)                              \

    static QGlobalStatic<TYPE > this_##NAME = { Q_BASIC_ATOMIC_INITIALIZER(0), false }

#define Q_GLOBAL_STATIC(TYPE, NAME)                                     \

    Q_GLOBAL_STATIC_INIT(TYPE, NAME);                                   \
    static TYPE *NAME()                                                 \
    {                                                                   \
        if (!this_##NAME.pointer && !this_##NAME.destroyed) {           \
            TYPE *x = new TYPE;                                         \
            if (!this_##NAME.pointer.testAndSetOrdered(0, x))           \
                delete x;                                               \
            else                                                        \
                static QGlobalStaticDeleter<TYPE > cleanup(this_##NAME); \
        }                                                               \
        return this_##NAME.pointer;                                     \
    }

 

Q_GLOBAL_STATIC:

1、先通过Q_GLOBAL_STATIC_INIT声明一个静态的全局变量(this_##NAME ),并初始化为0

2、声明一个名字叫做全局变量(NAME)的static的函数,用来取得这个全局变量

3、如果这个变量没初始化且没删除,就通过testAndSetOrdered以原子方式创建

4、创建成功,再定义一个函数内的QGlobalStaticDeleter来清理这个全局变量

5、函数返回最后结果

 

qt在每个arch上面都实现了原子操作,移植时候修改src/corelib/arch/qatomic_ARCH.h

参考文档: Implementing Atomic Operations

转载地址:https://blog.csdn.net/lclflash/article/details/19068111 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:QT中插件分析
下一篇:软件架构模式-读书笔记(5)-基于空间的架构

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2024年04月18日 13时17分49秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章