1.mainwindow.h
static MainWindow* getInstance();
2. mainwindow.cpp
Q_GLOBAL_STATIC(MainWindow,mainwindow)
static MainWindow* MainWindow::getInstance(){
return mainwindow();
}
这样就可以使用了;
有时间在看内部的实现方法;
Qt 源码
#define Q_GLOBAL_STATIC(TYPE, NAME) \
Q_GLOBAL_STATIC_WITH_ARGS(TYPE, NAME, ())
#define Q_GLOBAL_STATIC_WITH_ARGS(TYPE, NAME, ARGS) \
static QGlobalStatic<TYPE,Q_QGS_ ## NAME::innerFunction,Q_QGS_ ## NAME::guard> NAME;
struct QGlobalStatic
{
typedef T Type;
bool isDestroyed() const { return guard.load() <= QtGlobalStatic::Destroyed; }
bool exists() const { return guard.load() == QtGlobalStatic::Initialized; }
operator Type *() { if (isDestroyed()) return 0; return innerFunction(); }
Type *operator()() { if (isDestroyed()) return 0; return innerFunction(); }
Type *operator->()
{
Q_ASSERT_X(!isDestroyed(), "Q_GLOBAL_STATIC", "The global static was used after being destroyed");
return innerFunction();
}
Type &operator*()
{
Q_ASSERT_X(!isDestroyed(), "Q_GLOBAL_STATIC", "The global static was used after being destroyed");
return *innerFunction();
}
};
#define Q_GLOBAL_STATIC_INTERNAL(ARGS) \
Q_GLOBAL_STATIC_INTERNAL_DECORATION Type *innerFunction() \
{ \
struct HolderBase { \
~HolderBase() Q_DECL_NOTHROW \
{ if (guard.load() == QtGlobalStatic::Initialized) \
guard.store(QtGlobalStatic::Destroyed); } \
}; \
static struct Holder : public HolderBase { \
Type value; \
Holder() \
Q_DECL_NOEXCEPT_EXPR(noexcept(Type ARGS)) \
: value ARGS \
{ guard.store(QtGlobalStatic::Initialized); } \
} holder; \
return &holder.value; \
}
翻译完
static QGlobalStatic<MainWindow,Q_QGS_mainwindow::innerFunction,Q_QGS_mainwindow::guard> mainwindow;
typedef Type TYPE
所以 使用mainwindow()
Type *operator()() { if (isDestroyed()) return 0; return innerFunction(); }
返回一个Type 对象的指针;
innerFunction() 内部利用静态内部类构造对象 并进行析构;