简体   繁体   中英

Deleting objects in Qt Thread after thread finishes

I am newbee at QThreads and a problem that I am suspicious of deleting the objects when the program finishes.My program has a class that derived from 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 
  //               

  }

If I stop my program I see that some objects are not deleted correctly and my program does not work when I restart it.Actually I am not so familiar with Qt threads and i wonder when does the destructor of My_Class will be called? and am i doing the wrong thing?

You forgot to control lifetime of your timer (in My_Class::process ):

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

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

You should delete my_class=new My_Class(); manually. It will not be deleted on finished signal of thread, because there will be no event loop to process deleteLater slot.

I'm confused, why you don't want to declare my_class as member of My_application ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM