More than one instance of QApplication?
-
According to the API doc, one can not create more than one instance of QApplication.
However, the following code snippet shows one can have more than one instances
of QApplication.
@
QApplication app(argc, argv);
QApplication *pApp = new QApplication(argc, argv);
qDebug() << (pApp == &app); // false
qDebug() << (QApplication::instance() == &app); // false
qDebug() << (QApplication::instance() == pApp); // true
qDebug() << (QApplication::instance() == qApp); // true
@Actually, QApplication::instance() always refers to the latest created instance.
Why don't make QApplication a real "singleton"?
-
The documentation is correct -- if you create more than one object yourself, you get undefined behaviour (like what you're seeing).
QApplication is a subclass of QGuiApplication, which is a subclass of QCoreApplication. qApp is a QCoreApplication pointer.
Singletons and subclassing don't mix nicely -- QApplication's constructor will also construct a QGuiApplication and a QCoreApplication behind the scenes. Now we have 3 "objects", not a singleton.
-
Hi, I think you should get a compile error if your project is in Debug mode.