QCoreApplication on the heap

QCoreApplication on the heap

本文关键字:heap the on QCoreApplication      更新时间:2023-10-16

我有需要(例如构建库时(实例化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()的列表为空。

它似乎与此错误有关,该错误已固定在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();
}

我相信修复此错误的另一种方法是通过参考:

传递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

相关文章: