gpt4 book ai didi

c++ - 堆上的 QCoreApplication

转载 作者:行者123 更新时间:2023-11-30 05:13:41 25 4
gpt4 key购买 nike

我需要(例如在构建库时)在堆上实例化 QCoreApplication,我发现了以下奇怪的行为(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!
}

基本上,如果在分配对象后立即使用“qDebug()”,一切都会按预期进行。否则,arguments() 列表为空。

最佳答案

好像和this bug有关,它在 Qt 5.9 中得到修复并向后移植到 Qt 5.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();
}

关于c++ - 堆上的 QCoreApplication,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43825082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com