Reputation: 291
I have the need (for example when building a library) to instantiate QCoreApplication on the heap, and I found the following strange behavior (Qt 5.7):
#include <QCoreApplication>
#include <QDebug>
class Test
{
public:
Test(int argc, char *argv[]) {
m_app = new QCoreApplication(argc, argv);
//uncomment this line to make it work
//qDebug() << "test";
}
~Test() { delete m_app; }
private:
QCoreApplication* m_app;
};
int main(int argc, char *argv[])
{
Test test(argc, argv);
qDebug() << QCoreApplication::arguments(); //empty list!
}
Basically, everything works as expected if "qDebug()" is used just after allocating the object. If not, the list of arguments()
is empty.
Upvotes: 1
Views: 300
Reputation: 5466
I believe another way to fix this bug is to pass argc
by reference:
#include <QCoreApplication>
#include <QDebug>
class Test
{
public:
Test(int& argc, char *argv[]) {
m_app = new QCoreApplication(argc, argv);
//uncomment this line to make it work
//qDebug() << "test";
}
~Test() { delete m_app; }
private:
QCoreApplication* m_app;
};
int main(int argc, char *argv[])
{
Test test(argc, argv);
qDebug() << QCoreApplication::arguments(); //empty list!
}
In addition, you don't need to create QCoreApplication
on the heap, having it as an automatic member of Test
is fine, i.e. QCoreApplication m_app
.
Upvotes: 0
Reputation: 291
It seems to be related to this bug, which was fixed in Qt 5.9 and backported to Qt 5.6.3. The workaround is simply:
#include <QCoreApplication>
#include <QDebug>
class Test
{
public:
Test(int argc, char *argv[]) {
//allocate argc on the heap, too
m_argc = new int(argc);
m_app = new QCoreApplication(*m_argc, argv);
}
~Test() {
delete m_app;
delete m_argc;
}
private:
int* m_argc;
QCoreApplication* m_app;
};
int main(int argc, char *argv[])
{
Test test(argc, argv);
qDebug() << QCoreApplication::arguments();
}
Upvotes: 1