Home > database >  Using deleteLater() for an object with a cyclic timer
Using deleteLater() for an object with a cyclic timer

Time:01-25

I create an object of a class that has a QTimer that runs cyclically. The client of the program can request the removal of the task that the object is doing, which will delete the object. When using object->deleteLate(); the object is never deleted, but with delete object; it works.

Is this due to the timer field in the object running cyclically?

CodePudding user response:

The documentation for ~QObject says:

All signals to and from the object are automatically disconnected, and any pending posted events for the object are removed from the event queue. However, it is often safer to use deleteLater() rather than deleting a QObject subclass directly.

Emphasis is mine. In a note later in the same document

Warning: Deleting a QObject while pending events are waiting to be delivered can cause a crash. You must not delete the QObject directly if it exists in a different thread than the one currently executing. Use deleteLater() instead, which will cause the event loop to delete the object after all pending events have been delivered to it.

Emphasis is mine. This means your cyclic timer, upon re-adding itself, would cause the object to always have a pending event.

If you want to use deleteLater(), then your cyclic timer should detect whether a deleteLater() is in progress, and then cancel itself if so. Then, your deletion will occur after any other pending event has been cleared.

CodePudding user response:

Yes, it is likely that the timer field in the object is preventing the object from being deleted when you use object->deleteLater(). deleteLater() is a function that schedules the object for deletion, but it doesn't delete the object immediately. Instead, it posts a message to the event loop of the thread that the object lives in, asking it to delete the object when it's safe to do so. This is useful when you want to delete an object from a different thread than the one it was created in. However, if the object's timer is running and has not finished yet, the event loop will not be able to delete the object, because it is still in use. As a result, the object will not be deleted until the timer finishes. So, if you want to delete an object that has a running timer, you should stop the timer before calling deleteLater() or just call delete on the object.

Additionally, you should also take care of any other resources that the object might hold, such as file handlers, open sockets, etc. in order to avoid resource leaks and other issues.

  •  Tags:  
  • c qt
  • Related