Search code examples
c++qtqthread

How to release memory of Qthread object?


I have done something like this:

//in the mainwindow's constructor
QThread *thr = new QThread;
soundWorker * work = new soundWorker;
connect(this,SIGNAL(playsound()),work,SLOT(process()));
work->moveToThread(thr);
thr->start();

Shall I delete thr and work at the deconstructor of mainwindow?


Solution

  • You can use the default Qt way of managing memory by assigning a parent to the QThread, i.e. do this:

    QThread *thr = new QThread(this);//the mainwindow's is now the thread parent
    

    In Qt, parents are responsible for managing the memory of their children. Thus, the QThread will be automatically deleted when needed.

    Then, for your soundWorker, you have a few different solutions. If its lifetime is the same as your mainwindow, as you hint when you ask if you should delete it in the destructor of the mainwindow, you could simply make it a non-pointer member, and its storage duration would then become automatically handled.

    The parent thing is specific to Qt though. In general, when you deal with memory yourself, you should resort to wrappers (such as smart pointers) that enables RAII.

    Further reading: Qt Trees and ownership model