我需要(例如,在构建库时)在堆上实例化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/

10-09 08:56