[Interest] Automatic deletion of children of QObject

Andreas Pakulat apaku at gmx.de
Tue Jun 12 20:45:36 CEST 2012


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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20120612/829dfd45/attachment.html>


More information about the Interest mailing list