如何获得QObject::deleteLater(),以使对象为零?

时间:2022-03-14 18:45:53

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?

但是,如果我使用deleteLater()函数,我就失去了对它的控制。我不知道它是否是一个有效的项目,或者是否需要创建一个新的。我找到的解决办法是单独追踪国家,但是有没有更好的办法?

3 个解决方案

#1


16  

There is nothing wrong if you call deleteLater() on your object and then set your pointer to NULL. QT framework will safely delete the object for you.

如果您在对象上调用deleteLater(),然后将指针设置为空,则没有任何错误。QT框架将安全删除对象。

As an alternative you can also connect to destroyed signal to be notified of your object's destruction and set your pointer to NULL in that slot.

作为一种选择,您还可以连接到被销毁的信号,以通知您的对象的销毁,并将您的指针设置为空。

#2


9  

You can use QPointer if the object that is being deleted is a QObject. This will set it to NULL.

如果被删除的对象是一个QObject,则可以使用QPointer。这会将其设置为NULL。

#3


3  

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.

你的意思是“0指针”吗?在c++中,区分对象和指向它的指针比在Java中更重要。这里,它特别重要,因为如果你将对象为零,它的析构函数就不起作用了。如果您将一个指向对象的指针为零,那么就没有问题了,因为Qt将会添加一个指向“被删除的对象”列表的指针。

#1


16  

There is nothing wrong if you call deleteLater() on your object and then set your pointer to NULL. QT framework will safely delete the object for you.

如果您在对象上调用deleteLater(),然后将指针设置为空,则没有任何错误。QT框架将安全删除对象。

As an alternative you can also connect to destroyed signal to be notified of your object's destruction and set your pointer to NULL in that slot.

作为一种选择,您还可以连接到被销毁的信号,以通知您的对象的销毁,并将您的指针设置为空。

#2


9  

You can use QPointer if the object that is being deleted is a QObject. This will set it to NULL.

如果被删除的对象是一个QObject,则可以使用QPointer。这会将其设置为NULL。

#3


3  

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.

你的意思是“0指针”吗?在c++中,区分对象和指向它的指针比在Java中更重要。这里,它特别重要,因为如果你将对象为零,它的析构函数就不起作用了。如果您将一个指向对象的指针为零,那么就没有问题了,因为Qt将会添加一个指向“被删除的对象”列表的指针。