如何释放Qthread对象的内存? [英] How to release memory of Qthread object?

查看:95
本文介绍了如何释放Qthread对象的内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做过这样的事情:

//in the mainwindow's constructor
QThread *thr = new QThread;
soundWorker * work = new soundWorker;
connect(this,SIGNAL(playsound()),work,SLOT(process()));
work->moveToThread(thr);
thr->start();

我是否应该删除 thr 并在主窗口的析构函数处工作?

Shall I delete thr and work at the deconstructor of mainwindow?

推荐答案

您可以通过将父级分配给 QThread 来使用默认的 Qt 管理内存方式,即这样做:

You can use the default Qt way of managing memory by assigning a parent to the QThread, i.e. do this:

QThread *thr = new QThread(this);//the mainwindow's is now the thread parent

在 Qt 中,父母负责管理孩子的记忆.因此,QThread 会在需要时自动删除.

In Qt, parents are responsible for managing the memory of their children. Thus, the QThread will be automatically deleted when needed.

然后,对于您的 soundWorker,您有几种不同的解决方案.如果它的生命周期与您的 mainwindow 相同,正如您在询问是否应该在 mainwindow 的析构函数中删除它时所暗示的那样,您可以简单地将其设为非-指针成员,它的存储持续时间将被自动处理.

Then, for your soundWorker, you have a few different solutions. If its lifetime is the same as your mainwindow, as you hint when you ask if you should delete it in the destructor of the mainwindow, you could simply make it a non-pointer member, and its storage duration would then become automatically handled.

不过,父对象是特定于 Qt 的.一般来说,当您自己处理内存时,您应该求助于启用 <的包装器(例如智能指针)强>RAII.

The parent thing is specific to Qt though. In general, when you deal with memory yourself, you should resort to wrappers (such as smart pointers) that enables RAII.

进一步阅读:Qt 树和所有权模型

这篇关于如何释放Qthread对象的内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆