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