如何让 QObject::deleteLater() 将对象归零?
通常,当我删除一个对象时,我将其设置为零。这有助于我编写例程来检查对象不为零然后继续。
但是,如果我使用 deleteLater()
函数,我就失去了对它的控制。我不知道它是否有效,或者我是否需要创建一个新项目。我找到的解决方案只是单独跟踪状态,但是有更好的方法吗?
Normally when I delete an object I set it to zero. This helps in that I code my routines to check the object is not zero then proceed.
However if I use the deleteLater()
function I have lost control of it. I don't know if its a valid item or if I need to create a new one. The solution I found was just to keep track of the state separately however is there a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您对对象调用
deleteLater()
,然后将指针设置为nullptr
,则没有任何问题。 Qt 框架将安全地为您删除该对象。作为替代方案,您还可以连接到销毁信号以获取对象销毁的通知,并将指针设置为该槽中的
nullptr
。There is nothing wrong if you call
deleteLater()
on your object and then set your pointer tonullptr
. Qt framework will safely delete the object for you.As an alternative you can also connect to destroyed signal to be notified of your object's destruction and set your pointer to
nullptr
in that slot.如果要删除的对象是 QObject,则可以使用 QPointer。这会将其设置为 NULL。
You can use QPointer if the object that is being deleted is a QObject. This will set it to NULL.
您的意思是“将指针归零”吗?在 C++ 中,区分对象和指向它的指针比在 Java 中更重要。在这里,这一点尤其重要,因为如果将对象归零,它的析构函数将不起作用。如果将指向该对象的指针清零,没问题,因为 Qt 将添加另一个指向“要删除的对象”列表的指针。
Do you mean, "zero the pointer"? In C++ it's more important than in Java to make the distinction between the object and a pointer to it. Here, it's especially important, because if you zero the object its destructor won't work. If you zero a pointer to the object, no problem, because Qt will have added another pointer to the "objects-to-be-deleted" list.