本文介绍了何时使用deleteLater的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下代码段,是否可以安全地在qto的析构函数中为它可能管理的其他QT对象调用deleteLater?

Assuming I have the following snippet, is it safe to call deleteLater in qto's destructor for other QT objects it might administer?

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    MyQTObject qto;
    qto.show();
    return a.exec();
}

因为我已经使用泄漏检测器分析了类似的代码,并且所有调用了deleteLater的对象都没有正确释放,除非我用普通的delete替换了调用.如果我已正确理解这一点,则deleteLater仅在QT消息​​队列中注册一个删除事件.这可能是在main范围的末尾调用qto的析构函数而QT消息循环已经以a.exec的返回结尾的问题吗?因此,删除事件将永远不会被处理,实际上因为没有事件,甚至不会将其推送到消息队列中?

Because I've analyzed similar code like this with a leak detector and all the objects for which deleteLater was called, weren't deallocated correctly unless I replaced the call with a normal delete.If I've understood this correctly, deleteLater only registers a deletion event in the QT message queue. Can this be the problem that qto's destructor is called at the end of main's scope whereas the QT message loop already ends with the return from a.exec? Thus the deletion event will never be processed, in fact not even pushed into a message queue since there is none?

推荐答案

据我了解,当您需要从插槽调用中删除对象时,最常使用deleteLater.如果在这种情况下使用delete并且从插槽返回时引用了该对象,则会发生对未初始化内存的引用.

As I understand it, deleteLater is most often used when you require an object to be deleted from within the call to a slot. If delete is used in this case and the object is referenced when returning from the slot, a reference to uninitialised memory occurs.

因此,deleteLater通过在事件循环中放置一条消息来请求删除该对象,该消息在从插槽返回时在某个时候进行了处理,并且可以安全地删除.

Therefore, deleteLater requests that object to be deleted by placing a message on the event loop, which is processed at some point, on returning from the slot and it is safe to be deleted.

我希望在析构函数中使用deleteLater意味着该对象很可能超出范围,在其托管对象上调用deleteLater,但是在事件循环有机会删除该对象之前退出,就像从QApplication退出一样: :exec()将终止事件循环.

I expect that using deleteLater in the destructor means there's a likely chance that the object goes out of scope, calls deleteLater on its managed objects, but quits before the event loop has a chance to delete the objects, as exiting from QApplication::exec() will terminate the event loop.

这篇关于何时使用deleteLater的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 17:22