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

Thiago Macieira thiago.macieira at intel.com
Tue Aug 18 00:00:20 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. 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;
> }

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.

-- 
Thiago Macieira - thiago.macieira (AT) intel.com
  Software Architect - Intel Open Source Technology Center




More information about the Interest mailing list