scdmb scdmb - 3 months ago 17
C++ Question

Why is it allowed to create more than one QCoreApplication objects?

Looking at the following code:

#include <QDebug>
#include <QCoreApplication>

int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
qDebug() << QCoreApplication::instance(); // prints QCoreApplication(0x7ffd39656150)
QCoreApplication app2(argc, argv);
qDebug() << QCoreApplication::instance(); // prints QCoreApplication(0x7ffd39656160)

return 0;
}


It looks like that it's possible to create more than one QCoreApplication objects, but that should be a singleton. What does happen to the first created QCoreApplication object? Is it destroyed or will be there two event loops when exec is called for two objects?

Answer

That's illegal. You're probably running against a release build of Qt, with asserts disabled.

https://code.woboq.org/qt5/qtbase/src/corelib/kernel/qcoreapplication.cpp.html#742 makes it very clear that you cannot have two QCoreApplication alive at the same time:

void QCoreApplicationPrivate::init()
{
    Q_Q(QCoreApplication);

    initLocale();

    Q_ASSERT_X(!QCoreApplication::self, "QCoreApplication", "there should be only one application object");
    QCoreApplication::self = q;

    ....
Comments