[Interest] Automatic deletion of children of QObject
Jochen Becher
jochen_becher at gmx.de
Tue Jun 12 21:32:29 CEST 2012
As children are stored in a simple list and new children will be
appended to its end it would be very simple to delete them in reverse
order: Simply traverse the list from count()-1 to 0. This would be a
one-line-change in method deleteChildren().
Of course if I say "delete it in reverse order of creation" I mean:
"delete it in reverse order of being added to its parent". So if you
remove an object and re-add it to the same or another object it will be
deleted earlier.
I changed my code to use its own list to maintain the children just for
deletion within the order I need.
Regards, Jochen
Am Dienstag, den 12.06.2012, 20:45 +0200 schrieb Andreas Pakulat:
> Hi,
>
> On Tue, Jun 12, 2012 at 8:37 PM, Jochen Becher <jochen_becher at gmx.de>
> wrote:
> Hi,
>
> Think of the following code:
>
>
> QObject *parent = new QObject();
> QObject *childA = new QObject(parent);
> QObject *childB = new QObject)parent);
>
> delete parent;
>
>
> In which order would you expect childA and childB gets
> deleted? I would
> expect childB first and childA second. This would be same
> behavior as in
> using normal variables:
>
> QObject parent;
> QObject childA(&parent);
> QObject childB(&parent);
>
> Here, on leaving the scope childB would be deleted first,
> childA second
> and parent last.
>
> Isn't it a bug in Qt to delete children in the same order
> there were
> added to a parent instead of the reverse order?
>
>
> No, Qt makes no such guarantees. In fact it doesn't guarantee any
> specific order of destruction for the children, if you rely on any
> order here, your code is buggy.
>
>
> Its also not possible to actually do this, since you can add/remove
> childs from the list during the runtime of the program and the QObject
> cannot know wether the last-added object is really the one to be
> destroyed first (in your ideal scenario) or wether its maybe the one
> created first but was removed and re-added later.
>
>
> Since QObject keeps an ordered list of its children, I think its
> reasonable that they simply run over it from beginning to end and
> destroy the childs instead of going through the extra hoop of running
> from end to beginning.
>
>
> Andreas
More information about the Interest
mailing list