我是 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/