在 QObject::moveToThread 中移动语义
Move semantics in QObject::moveToThread
在 QThread class 的文档中,一个示例性设置的工作原理如下:
public:
Controller() {
Worker *worker = new Worker;
worker->moveToThread(&workerThread);
//some connects to thread and worker
workerThread.start();
}
~Controller() {
workerThread.quit();
workerThread.wait();
}
Qt 是否在此处使用 moveToThread(...)
函数实现了实际的移动语义? IE。线程是否在完成后负责取消分配 Worker 对象,因为 Controller()
中分配的 Worker*
从未在任何地方显式删除?
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?
什么 moveToThread
意味着 myObject
的插槽将在该 QThread 的事件循环的上下文中执行:
来自 Qt documentation:
By default, run() starts the event loop by calling exec() and runs a
Qt event loop inside the thread.
就所有权而言,在此上下文中,moveToThread 与内存管理方面的所有权无关,而是与线程执行槽方面的所有权有关。默认情况下,所有插槽都在主 Qt 事件循环中执行。要将其移动到线程的那个,请调用 moveToThread
...
moveToThread
不会转让所有权。
在链接示例中,此行将确保在线程完成后删除工作线程:
connect(&workerThread, &QThread::finished, worker, &QObject::deleteLater);
看来 QThreadPool
更适合您给出的示例。如文档中所述:
Worker *worker = new Worker();
// QThreadPool takes ownership and deletes 'worker' automatically
QThreadPool::globalInstance()->start(worker);
你的Worker
class需要继承QRunnable
并实现运行()虚函数
在 QThread class 的文档中,一个示例性设置的工作原理如下:
public:
Controller() {
Worker *worker = new Worker;
worker->moveToThread(&workerThread);
//some connects to thread and worker
workerThread.start();
}
~Controller() {
workerThread.quit();
workerThread.wait();
}
Qt 是否在此处使用 moveToThread(...)
函数实现了实际的移动语义? IE。线程是否在完成后负责取消分配 Worker 对象,因为 Controller()
中分配的 Worker*
从未在任何地方显式删除?
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?
什么 moveToThread
意味着 myObject
的插槽将在该 QThread 的事件循环的上下文中执行:
来自 Qt documentation:
By default, run() starts the event loop by calling exec() and runs a Qt event loop inside the thread.
就所有权而言,在此上下文中,moveToThread 与内存管理方面的所有权无关,而是与线程执行槽方面的所有权有关。默认情况下,所有插槽都在主 Qt 事件循环中执行。要将其移动到线程的那个,请调用 moveToThread
...
moveToThread
不会转让所有权。
在链接示例中,此行将确保在线程完成后删除工作线程:
connect(&workerThread, &QThread::finished, worker, &QObject::deleteLater);
看来 QThreadPool
更适合您给出的示例。如文档中所述:
Worker *worker = new Worker();
// QThreadPool takes ownership and deletes 'worker' automatically
QThreadPool::globalInstance()->start(worker);
你的Worker
class需要继承QRunnable
并实现运行()虚函数