QThreads - 为什么在构造函数中分配内存而不是普通的类成员?

时间:2018-06-07 04:49:51

标签: c++ qt qthread

http://doc.qt.io/qt-5/qthread.html

class Controller : public QObject
{
    Q_OBJECT
    QThread workerThread;
public:
    Controller() {
        Worker *worker = new Worker;
        worker->moveToThread(&workerThread);
        connect(&workerThread, &QThread::finished, worker, &QObject::deleteLater);
        connect(this, &Controller::operate, worker, &Worker::doWork);
        connect(worker, &Worker::resultReady, this, &Controller::handleResults);
        workerThread.start();
    }

我的方式:

class Controller: public QObject
{
    Q_OBJECT
public:
    Worker  objWorker;
    QThread objQThread;

    Controller();
    ~Controller();

public slots:
    void receiveImage();
};

Controller::Controller()
{
    objWorker.moveToThread( &objQThread );

    connect( &objWorker, &Worker::imageReady, this, &Controller::receiveImage );

    objQThread.start();
}

他们的方法在某种程度上比我的好吗?在哪种情况下哪个应该是首选的?

1 个答案:

答案 0 :(得分:0)

来自:http://doc.qt.io/qt-5/qthread.html

  

从Qt 4.8开始,可以释放存在的对象   通过将finished()信号连接到刚刚结束的线程   的QObject :: deleteLater()。

这只能通过创建Worker类的指针对象并为其分配内存来实现。