[SOLVED] self-deleting objects
-
This is pure gold, Andre :) Very nice trick.
-
@Andre: I've changed the scenario in my original post slightly to more accurately reflect my setup: A signals B, B calls method of C, C deletes A, causing a seg fault. The timing of the deletion is important because C then reconstructs A with new parameters. A's signal does appear as its last instruction, but Qt Creator's debugger seems to indicate that A never gets a chance to exit before B's slot fully executes. That's why I was wondering whether I need another thread.
@KA510: I tried deleteLater(). The problem, as mentioned above, is that the deletion needs to be accompanied by a reconstruction of the object, and I don't see any way to schedule them together.
-
Sorry, but no, I do not see that sequence working like this.
What you could try, is connect the signal from A to B as a queued signal/slot connection. That way, A will have time to exit the procecure where the signal is emitted in a controlled way. Only when control returns to the eventloop, the signal will be delivered, and you can savely delete A.
-
While queued connections ARE used between QThreads, they can be used independently for connections within a single thread. Adding a Qt::ConnectionType parameter to your connect() call to use a Qt::QueuedConnection just instructs the signal/slot system to push the call to your slot onto a queue, where the event loop will pick it up and execute it on the next event loop iteration. This is in contrast to the slot being called directly. Check the "QObject::connect()":/doc/qt-4.8/qobject.html#connect documentation for more details.
-
Thanks for sharing a very interesting scenario and thanks Andre for a very cool tip :)
-
[quote author="planarian" date="1348164616"]Adding Qt::QueuedConnection to the connect calls fixed it. Thanks very much, everyone![/quote]
Note that the advice I gave still goes: as your class has no control over how it is connected to other components (directly or via a queued connection), it is a good idea to be careful about what happens when emitting a signal.
Still, I am happy to hear that using a queued connection solved your problem.
-
[quote author="Sam" date="1348236234"]Bravo!!! That a cool trick !!! thanks Andre
I wish we could also dockmark these posts/topics like other pages. Or May be we can add a page to Wiki.
[/quote]
Thanks :-)To give credit where credit is due: I had quite a bit of inspiration from "this":http://delta.affinix.com/dor/ page.