【问题标题】:QCoreApplication on the heap堆上的 QCoreApplication
【发布时间】:2017-05-06 20:27:47
【问题描述】:

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

【问题讨论】:

    标签: c++ qt


    【解决方案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();
    }
    

    【讨论】:

      【解决方案2】:

      我相信修复此错误的另一种方法是通过引用传递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。

      【讨论】:

      • 我同意,这也应该可以,虽然我还没有测试过。确实,对于这个例子,没有必要在堆上分配QCoreApplication ......但是我也不需要Test 类。在实际代码中,Test 和 QCoreApplication 的实例没有相同的生命周期。但是,如果在堆栈上分配了 QCoreApplication,则该错误不会出现。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-12
      • 2010-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多