[Interest] How to get destructor called in object that was moved to a thread?

Murphy, Sean smurphy at walbro.com
Wed Aug 19 04:10:17 CEST 2015


> On Monday 17 August 2015 21:34:17 Murphy, Sean wrote:
> > I'm struggling to get my destructor called in a class of mine that is
> > moved to a separate thread
> 
> You must call it in the thread that the object is associated with.
> 
> > My mainwindow's .cpp file:
> > MainWindow::MainWindow(QWidget *parent) {
> >   mine = new myClass();
> >   myThread = new QThread(this);
> >   mine->moveToThread(myThread);
> >   myThread->start();
> > }
> 
> You have two options:
> 
> delete it in the myThread thread once you no longer need it. 

That's not an option without subclassing QThread though right? Since the way I'm doing it, the only object
that is lives in the myThread thread is the object I'm trying to delete. Or am I misunderstanding something?

> You can also
> connect its destroyed() signal to the thread's quit() slot, so the thread will
> exit automatically once the object dies. And you can achieve that through:
> 
> >   MainWindow::~MainWindow()
> > {
> >     myThread ->exit();
> 
> Replace the line above with
> 	mine->deleteLater();
> 	myThread->wait();
> 
> >     delete ui;
> > }

This seemed to do the trick.

> 
> The other option is to move the object back to the main thread before
> exiting that thread, and then deleting it in the destructor once the thread has
> exited. This is a lot harder and, as far as I can tell, unnecessary.

Then I'll avoid it!

Thanks,
Sean



More information about the Interest mailing list