为什么这个类的析构函数没有被调用?
我有两个类 - 一个在主线程中运行并执行 GUI 操作,另一个执行一些计算并发出网络请求。
// A member of the class that runs in the main thread
QThread thread;
以下是在主线程中运行的类的初始化方法的片段:
// Create the class that runs in the other thread and move it there
CServerThread * server = new CServerThread;
server->moveToThread(&thread);
// When the thread terminates, we want the object destroyed
connect(&thread, SIGNAL(finished()), server, SLOT(deleteLater()));
thread.start();
在主线程中运行的类的析构函数中:
if(thread.isRunning())
{
thread.quit();
thread.wait();
}
我期望发生的是线程终止并销毁 CServerThread 的实例类。但是,CServerThread
类的析构函数没有被调用。
I have two classes - one that runs in the main thread and performs GUI operations and another that performs some calculations and makes network requests.
// A member of the class that runs in the main thread
QThread thread;
Here is a snippet from the initialization method of the class that runs in the main thread:
// Create the class that runs in the other thread and move it there
CServerThread * server = new CServerThread;
server->moveToThread(&thread);
// When the thread terminates, we want the object destroyed
connect(&thread, SIGNAL(finished()), server, SLOT(deleteLater()));
thread.start();
In the destructor for the class that runs in the main thread:
if(thread.isRunning())
{
thread.quit();
thread.wait();
}
What I expect to happen is the thread terminates and destroys the instance of the CServerThread
class. However, the destructor for the CServerThread
class is not getting invoked.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
QThread::quit()
停止该线程的事件循环。但是
QObject::deleteLater()
需要“拥有”线程处于活动状态的事件循环:因此,您的对象的析构函数将不会运行,
finished
信号的触发为时已晚。考虑下面的人为示例:
如果调用:
输出将为:
finished
在wait
完成后触发。您的deleteLater
连接要生效已经太晚了,该线程的事件循环已经死了。QThread::quit()
stops the event loop for that thread.But
QObject::deleteLater()
needs the event loop for the "owning" thread to be active:So your object's destructor will not run, the
finished
signal is fired too late for that.Consider the contrived example below:
If you call:
The output will be:
finished
is triggered after thewait
is done. Too late for yourdeleteLater
connection to be effective, that thread's event loop is already dead.