2017-05-06 49 views
1

我有需要(例如建立时库)在堆上实例化QCoreApplication,我发现以下奇怪的行为(QT 5.7):QCoreApplication堆上

#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()的列表为空。

回答

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(); 
} 
0

我相信另一种方式来修复这个bug是按引用传递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

+0

我同意,也应该工作,虽然我还没有测试过。对于这个例子来说,没有必要在堆上分配'QCoreApplication' ......但是我不需要'Test'类。在真实代码中,'Test'和'QCoreApplication'的实例不具有相同的生命周期。但是,如果'QCoreApplication'被分配到堆栈上,错误就不会显示出来。 – matpen