c++ - 线程完成后删除Qt Thread中的对象

标签 c++ multithreading qt

我是 QThreads 的新手,我怀疑在程序完成时删除对象的问题。我的程序有一个派生自 QObject 的类:

class My_application: public QCoreApplication{
   ....
   ....
};

class My_Class: public QObject{
  ...
  ...
}; 

void My_Class::process{

     QTimer timer=new QTimer();
     timer->setInterval(time);
     connect(timer,SIGNAL(timeout()),this,SLOT(dowork()));
     timer->start(); 

} 

 My_application::My_application:QCoreApplication{

    my_class=new My_Class();

    QThread thread=new QThread();

    my_class->moveToThread(thread);

    connect(thread,SIGNAL(started()),my_class,SLOT(process())) ;

    connect(my_class,SIGNAL(finished()),thread,SLOT(quit())) ;

    connect(thread,SIGNAL(finished()),thread,SLOT(deletelater())) ;

    connect(my_class,SIGNAL(finished()),my_class,SLOT(deletelater())) ;        


 }

   void My_Class::dowork(){

  //here doing the work with timer elapsed.Doing work with some buffer and send data 
  //               

  }

如果我停止我的程序,我会看到一些对象没有被正确删除,并且当我重新启动它时我的程序不工作。实际上我对 Qt 线程不太熟悉,我想知道什么时候调用 My_Class 的析构函数?我做错了吗?

最佳答案

您忘记控制计时器的生命周期(在 My_Class::process 中):

connect( this, SIGNAL( destroyed() ), timer, SLOT( deleteLater() ) );

QTimer timer=new QTimer( **this** );

您应该手动删除 my_class=new My_Class();。它不会在线程的finished 信号时被删除,因为没有事件循环来处理deleteLater 槽。

我很困惑,为什么你不想将 my_class 声明为 My_application 的成员?

关于c++ - 线程完成后删除Qt Thread中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22090505/

相关文章:

java - Hibernate session 在初始提交失败后未刷新数据库中的数据

c++ - 复制线程安全吗?

c++ - Qt 未解析的外部符号

qt - 单击时在 QWidget 上绘制矩形叠加层

c++ - 无锁双向链表的原子操作

c++ - 当主线程显然未被阻塞时,QProgressDialog卡住

c++ - 在源文件中定义但在任何函数定义之外的变量的范围是什么?

java - 在线程上调用不同的方法

c++ - 调整半透明 Qt 小部件大小时黑色闪烁(仅当启用 Aero 时)?

c++ - 配置:错误:无法链接到 libboost_atomic