如果将QThread的完成信号连接到deleteLater,则必须删除在QThread上运行的对象吗?

时间:2019-07-17 21:59:34

标签: c++ qt qthread

所以我在构造函数中有以下代码。

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

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

任何我在析构函数中都有以下代码。

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

尽管已完成m_someObjectm_thread的{​​{1}}插槽的连接,我是否仍需要删除deleteLater

1 个答案:

答案 0 :(得分:1)

否,没有必要。只要线程最终发出结束,连接就可以完全按照您想要的方式进行操作。请参见以下代码:

#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;
}

输出符合预期:

c'tor
d'tor

请注意,由于该代码段缺少主代码,因此不会立即进行编译。