[Qt-interest] QObject destructor
Nikos Chantziaras
realnc at arcor.de
Tue May 4 21:57:15 CEST 2010
On 05/04/2010 10:50 PM, Nikos Chantziaras wrote:
> On 05/04/2010 10:43 PM, Yifei Li wrote:
>> Hi folks,
>>
>> I'm wondering if QObject destructor will delete the object's
>> children.
>>
>> For example, I have my own class MyWidget, and in its constructor
>> widgets are created on the stack with parent being the MyWidget
>> object. So do I need to delete all the widgets created on the stack
>> in MyWidget's destructor?
>
> Don't create widgets on the stack if they have a parent. Never.
> ~QObject() will try to delete them, and since they're on the stack, this
> will bomb at some point.
I should have provided more detail here. The correct phrase would be:
Don't create widgets on the stack if they have a parent *and
the parent is deleted before the children go out of scope*.
For example, this is not OK:
QWidget* parent = new QWidget;
QWidget child(parent);
delete parent;
However, this is OK:
QWidget* parent = new QWidget;
{
QWidget child(parent);
}
delete parent;
That's because when 'child' goes out of scope, its destructor will
remove it from its parent's child list.
More information about the Qt-interest-old
mailing list