多线程导致Qt运行时报错
Multi-threads cause the runtime error in Qt
当我尝试在 Qt 中执行多线程时,例如:
如果我像这样在另一个 class 中创建一个 class 对象:
QThread thread;
Worker worker;
worker.moveToThread(thread);
关闭程序会导致运行时错误
但是如果我像这样通过指针创建 class 对象:
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()));
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
当我尝试在 Qt 中执行多线程时,例如:
如果我像这样在另一个 class 中创建一个 class 对象:
QThread thread;
Worker worker;
worker.moveToThread(thread);
关闭程序会导致运行时错误
但是如果我像这样通过指针创建 class 对象:
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()));
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