• qt 实现单例


    头文件:

    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

  • 相关阅读:
    云计算被视为继大型计算机、个人计算机、互联网之后的第4次IT产业革命,顺应了当前各行业整合计算资源和服务能力的要求(转)
    hdu1172猜数字
    or1200构建sopc系统之软件环境搭建
    Log4cpp介绍及使用
    JAVA实现HTTPserver端
    站点防止攻击
    opencv是什么
    RBAC权限管理
    一分钟制作U盘版BT3
    为开发用途mac电脑瘦身
  • 原文地址:https://www.cnblogs.com/cute/p/2499060.html
Copyright © 2020-2023  润新知