Important: Please read the Qt Code of Conduct -

[SOLVED] A question on QObject child deletion

  • A while ago I was developing a class to manage the lifetime of child objects, and I used recursive deletion, when the root object is scheduled for deletion it schedules the deletion of its children, the children do the same and deletion is bottom to top, the root item is the last one deleted.

    When I was toying with QObject derived custom classes with a cout in the destructor I noticed the order of deletion seems to be the other way around - top to bottom, the root object is deleted first, then children, then grandchildren and so on. Is this really the case, and if so I am curious of the basic principle this is achieved?

  • No, what you are seeing is an effect of subclassing, I think. You have to understand the order in which constructors and destructors are run for an object. Objects are build from the inside out, and destructed from the outside in. In your case, that means that first the code in the destructor of your root object is ran. That produces debug output. Then, the code for the destructor of the parent class of your root object runs (I will assume all classes directly inherit QObject for simplicity). The QObject destructor will in turn delete it's children before it finished itself. The children are destructed in the same order: outside first. That means that again your own class' destructor will produce some debug output, and only then the base class's destructor is run, which will again first destruct it's own children. Etc.

    So, the output you will see produced, will indeed look like the destruction is done from the root towards the decendant objects, and in a way that is true. However, you have to realize that the destructor of an object only finishes when all the destructors of it's child classes have finished running. So, the root object is the first to start destructing, but the last to finish.

  • So the only reason the destructors appear in reverse order of my own implementation is with QObject I get the debug message before child deletion and in my case it was after child deletion? This causes the destructor message to appear after child deletion is complete not as the destructor is entered. I had this possibility in mind, but still was interested if there is a way to delete children without recursion, just in case of a scenario of too many children that could overload and crash the function call stack. That's why I was confused, and assumed there is some trickery that destroys an object and stores its children aside and destroys them afterwards. Sort of child deletion outside the destructor...

    Thanks :)

  • Well, if you want to be sure, I'd invite you to take a look at the source code for the destructor of QObject. It should make it clear how it works exactly.

  • Yes, I noticed it is pretty straightforward, not that I didn't trust you :P

Log in to reply