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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值