There is an object of class QNetworkReply. There is a slot (in some other object) connected to its finished() signal. Signals are synchronous (the default ones). There is only one thread.
At some moment of time I want to get rid of both of the objects. No more signals or anything from them. I want them gone. Well, I thought, I'll use
delete obj1; delete obj2;
But can I really? The specs for ~QObject say:
Deleting a QObject while pending events are waiting to be delivered can cause a crash.
What are the 'pending events'?
Could that mean that while I'm calling my delete
, there are already some 'pending events' to be delivered and that they may cause a crash and I cannot really check if there are any?
So let's say I call:
obj1->deleteLater(); obj2->deleteLater();
To be safe.
But, am I really safe? The deleteLater
adds an event that will be handled in the main loop when control gets there. Can there be some pending events (signals) for obj1
or obj2
already there, waiting to be handled in the main loop before deleteLater will be handled? That would be very unfortunate. I don't want to write code checking for 'somewhat deleted' status and ignoring the incoming signal in all of my slots.
obj->disconnect(); obj->deleteLater();
is the right way to go: – CapacitatedeleteLater()
simply posts aQDeferredDeleteEvent
to the object thatdeleteLater()
was invoked on. When that event is received by the QObject its event handler will ultimately invoke regulardelete
which in turn calls the QObject's destructor. Signal disconnection does not occur until the end of the destructor, therefore I'd guess that the QObject will run slots which are invoked by DirectConnection signals which are emitted after the call todeleteLater()
but before the event loop returns. – Weber