Search code examples
c++multithreadingqtqthread

deallocate objects that live in a thread that has just ended, by connecting the finished() signal to QObject::deleteLater()


From: http://doc.qt.io/qt-5/qthread.html#details

From Qt 4.8 onwards, it is possible to deallocate objects that live in a thread that has just ended, by connecting the finished() signal to QObject::deleteLater().

Does this mean if I connect finished() signal to QObject::deleteLater() I won't have to worry about memory leaks in the worker thread?

What objects of worker thread class is it going to deallocate on its own?

connect(workerThread, &WorkerThread::finished, workerThread, &QObject::deleteLater); From : doc.qt.io/qt-5/qthread.html#details

They have shown workerthread's object connected to deleteLater slot. Now does this mean that all objects which I allocate memory to inside the worker class will get automatically deleted?


Solution

  • If a QThread ends (when it run() method returns) it sends the signal QThread::finished. Every QObject whose deleteLater slot is connected to this signal gets deleted.

    If you connect the QThread::finished() signal to QObject::deleteLater() method of the worker object as mentioned in the documentation of QThread (http://doc.qt.io/qt-5/qthread.html#details), then the worker is deleted after the QThread has finished. All other QObjects which you have created within the worker will still exist. If you want them to be deleted too you have to either connect them to the same QThread::finished() signal or you use the parent-child-mechanism by setting the worker object as parent of the other object (either by passing it as parent in the constructor (http://doc.qt.io/qt-5/qobject.html#QObject) or by setting it explicitly with void QObject::setParent(QObject *parent) (http://doc.qt.io/qt-5/qobject.html#setParent).