c++ - 未调用 QCoreApplication 析构函数

标签 c++ c qt

我有一个派生自 QCoreApplication 类的应用程序,它有一个子线程成员。当我删除应用程序对象时,它有时会删除,有时不会。

class My_class :public QCoreApplication{
   private: 
   My_object* obj;
   QThread *th;
   public:
   My_class(){
      obj=new My_object();
      th= new QThread();
      obj->movetoThread(th);  // so it starts to run   
   }  
   ~My_class(){
      delete obj;       
      cout<<" App Destructor called"<<endl;
      }

   static void exit_(){quit();}        
 };

 // So in main I suddenly close my application and i want to exit and delete obj;
  int main()
  {
      My_class app;

      signal(SIGTERM,&app.exit_); 
      signal(SIGINT,&app.exit_); 
      signal(SIGBREAK,&app.exit_); 
      return app.exec();
  }
  // The obj destructor is;
  ~My_object::My_object(){cout<<"Object dest called"<<endl;}
  // The output of my program always writes "Object dest called"
  //But sometimes writes " App Destructor called".

所以我的程序总是进入 obj 的 destructpr 但有时它会进入应用程序析构函数,有时不会。如何实现?

最佳答案

您可能对使用 post 程序销毁记录感兴趣 here .

在这种情况下,您可以注册一个 post 例程来清除您存储在给定集合中的所有线程:

 QList<QThread*> myThreads;
 static void cleanup_threads()
 {
     foreach (QThread thread, myThreads) {
         // cleanup the thread and delete it
     }
 }

 int main(int argc, char **argv) {
     QCoreApplication app(argc, argv);
     qAddPostRoutine(cleanup_threads);

     // setup signal handlers
     // create threads
     return app.exec();
 }

除非您确切地知道自己在做什么,否则这种方法可能非常危险。首选方法是创建另一个派生自 QObject 的类,您可以将线程作为父类:

class MyThreadManager : public QObject {
    MyThreadManager(QObject *parent = 0) 
        : QObject(parent) 
    {
        for (int i = 0; i < 5; ++i) {
            MyThread *thread = new MyThread(this);
            // configure the thread object
            thread->start();

            // maybe add it to a local collection for later access: 
            // m_threads.append(thread);
        }
    }
};

int main(int argc, char **argv) {
    QCoreApplication app(argc, argv);
    // setup signal handlers
    MyThreadManager manager;
    return app.exec();
}

这样,您的所有线程都以同一个对象为父对象,该对象在销毁时由父对象的 QObjectCleanupHandler 清除。

关于c++ - 未调用 QCoreApplication 析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23293332/

相关文章:

linux - qgetenv 返回 NULL

c++ - 将 QObject 接口(interface)信号连接到 lambda 插槽

c++ - 如何强制 xcode 使用正确的 iostream header C++

c++ - 混合 QML/C++ 应用程序在部署后不会显示任何内容

c - 为什么函数指针可以带或不带运算符地址使用?

c - 你好。我的程序总是无法创建我期望的字符串输出。你能注意到一个缺陷吗?

c - 如何在cygwin下AllocConsole + Stdout重定向

c++ - BlackBerry 10 中的反向地理编码

C++特殊方法可见性

c++ - 尝试获取具有自定义类型的 DBus 属性时出现 fatal error