2017-05-06 83 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