Search code examples
c++qtqthread

Is it necessary to delete an object if that runs on a QThread if finished signal of QThread is connected to deleteLater?


So I have the following code in the constructor.

m_someObject = new SomeObject();
m_someObject->moveToThread(&m_thread);
m_thread.start();

connect(&m_thread, &QThread::finished, m_someObject, &QObject::deleteLater);

Any I have the following code in the destructor.

 m_thread.terminate();
 while (m_thread.isRunning())
 {
 }

Do I still have to delete m_someObject despite having finished of m_thread connected to deleteLater slot of m_someObject?


Solution

  • No it is not necessary. The connection should do exactly what you want as long as the thread does emit finished eventually. See the following Code:

    #include <QObject>
    #include <QThread>
    #include <iostream>
    
    class Test : public QObject {
        Q_OBJECT
    public:
        Test(){
            std::cout <<"c'tor" << std::endl;
        }
        ~Test(){
            std::cout << "d'tor" << std::endl;
        }
    };
    
    void startThread(){
        QThread* thr = new QThread();
        Test* test = new Test();
        connect(thr, &QThread::finished, test, &QObject::deleteLater);
        test->moveToThread( thr );
        thr->start();
        thr->quit();
        thr->wait();
        delete thr;
    }
    

    The output is as expected:

    c'tor
    d'tor
    

    Note that the snippet wont compile right away since its missing a main.