关于QObject::deleteLater()是否会造成内存泄漏

luike 2018-05-30 08:30:15
一个继承与QThread,重写run的类,如
class CMyThread : public QThread
{
private:
void run();
}
而run的实现是这样
void CMyThread ::run()
{
QTimer timer;//定时器,做超时检测
QEventLoop loop;
connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));
m_pLabel = new MyLabel;
timer.start(100);
loop.exec();
m_pLabel->deleteLater();
}
其中m_pLabel 是一个派生于QObject的类对象。
CMyThread 类对象在主UI线程中创建并start,那么这里m_pLabel是否能够被析构?是否存在内存泄漏?
我的理解是,定时器时间到,loop执行了quit之后,当前线程中就没有消息循环了,deleteLater发送的删除消息没有消息循环接收,也就没机会执行。不知道理解的正确不正确?
...全文
892 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
realMiga 2018-07-24
  • 打赏
  • 举报
回复
所有deleteLater 在qt的作用和用法是什么呢
luike 2018-05-31
  • 打赏
  • 举报
回复
引用 2 楼 dext 的回复:
按道理来讲 会被正确释放。因为,deleteLater会加入到 事件队列中 时间队列 析构时 也会被析构。但是,你的最大问题是 在一个Non-GUI 的线程里创建 GUI widget,这个行为在Qt规范中禁止的,所有代码即使执行正确,行为也是不确定的。
3Q,又回去翻了下文档,这个问题在QT4.8版本之后已经修复,我用的是5.5.1,担心多余了,3Q [slot] void QObject::deleteLater() Schedules this object for deletion. The object will be deleted when control returns to the event loop. If the event loop is not running when this function is called (e.g. deleteLater() is called on an object before QCoreApplication::exec()), the object will be deleted once the event loop is started. If deleteLater() is called after the main event loop has stopped, the object will not be deleted. Since Qt 4.8, if deleteLater() is called on an object that lives in a thread with no running event loop, the object will be destroyed when the thread finishes. Note that entering and leaving a new event loop (e.g., by opening a modal dialog) will not perform the deferred deletion; for the object to be deleted, the control must return to the event loop from which deleteLater() was called. Note: It is safe to call this function more than once; when the first deferred deletion event is delivered, any pending events for the object are removed from the event queue.
dext 2018-05-30
  • 打赏
  • 举报
回复
按道理来讲 会被正确释放。因为,deleteLater会加入到 事件队列中 时间队列 析构时 也会被析构。但是,你的最大问题是 在一个Non-GUI 的线程里创建 GUI widget,这个行为在Qt规范中禁止的,所有代码即使执行正确,行为也是不确定的。
luike 2018-05-30
  • 打赏
  • 举报
回复
顶一下,搞得有点懵逼

16,203

社区成员

发帖
与我相关
我的任务
社区描述
Qt 是一个跨平台应用程序框架。通过使用 Qt,您可以一次性开发应用程序和用户界面,然后将其部署到多个桌面和嵌入式操作系统,而无需重复编写源代码。
社区管理员
  • Qt
  • 亭台六七座
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧