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

私はこのバグを修正する別の方法は、参照によって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

関連する問題