c++qtqthreadownership-semantics

Move semantics in QObject::moveToThread


In the documentation of the QThread class one exemplary setup works like so:

public:
Controller() {
    Worker *worker = new Worker;
    worker->moveToThread(&workerThread);
    //some connects to thread and worker
    workerThread.start();
}
~Controller() {
    workerThread.quit();
    workerThread.wait();
}

Is Qt implementing actual move semantics with the moveToThread(...) function here? I.e. does the thread take care of de-allocating the Worker object once it finishes, as the Worker* allocated in Controller() is never deleted explicitly anywhere?


Solution

  • moveToThread will not transfer ownership.

    In the linked example this line will make sure the worker is deleted after the thread finished:

    connect(&workerThread, &QThread::finished, worker, &QObject::deleteLater);