標頭檔:
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