QCoreApplication在堆上

时间:2017-05-06 20:27:48

标签: c++ qt

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

2 个答案:

答案 0 :(得分:1)

它似乎与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();
}

答案 1 :(得分:0)

我认为另一种解决此错误的方法是通过引用传递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