我需要(例如在构建库时)在堆上实例化QCoreApplication,并且我发现了以下奇怪的行为(Qt5.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!
}基本上,如果在分配对象后立即使用"qDebug()“,则一切都按预期进行。如果不是,则arguments()列表为空。
发布于 2017-05-07 04:27:48
它似乎与this bug有关,它已在Qt5.9中修复,并向后移植到Qt5.6.3。解决方法很简单:
#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();
}发布于 2017-05-09 00:57:30
我认为修复这个错误的另一种方法是通过引用传递argc:
#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!
}此外,你不需要在堆上创建QCoreApplication,让它作为Test的自动成员就可以了,比如QCoreApplication m_app。
https://stackoverflow.com/questions/43825082
复制相似问题