【问题标题】:Multi-threads cause the runtime error in Qt多线程导致Qt中的运行时错误
【发布时间】:2018-01-12 02:14:20
【问题描述】:

当我尝试在 Qt 中做多线程时,例如:
如果我像这样在另一个类中创建一个类对象:

QThread thread;
Worker worker;
worker.moveToThread(thread);

当我关闭程序时会导致运行时错误。

但是如果我像这样通过指针创建类对象:

QThread* thread = new QThread;
Worker* worker = new Worker();
worker->moveToThread(thread);

不会出错。为什么我必须这样做?

并且我必须在使用后删除指针吗?如果我不这样做,那会导致内存泄漏吗?我看到很多教程都这样删除它们:

connect(worker, SIGNAL (finished()), thread, SLOT (quit()));
connect(worker, SIGNAL (finished()), worker, SLOT (deleteLater()));
connect(thread, SIGNAL (finished()), thread, SLOT (deleteLater()));

【问题讨论】:

    标签: c++ multithreading qt qthread


    【解决方案1】:

    Qt 通常管理其对象的内存。很多文档都这么说,但不是全部。

    您的运行时错误是由双重删除引起的。在第一个示例中,当worker 超出范围时,它将被破坏,Qt 也会尝试delete 它。在第二个示例中,只有 Qt 会删除它,而您不会。

    如果你看向Qt's own documentation of this,你会看到他们在做同样的事情:

    Controller() {
        Worker *worker = new Worker;
        worker->moveToThread(&workerThread);
       ...
    } // notice worker was not cleaned up here, which implies moveToThread takes ownership
    

    但是,moveToThread's documentation isn't clear on this

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多