我不明白Qt如何删除所有QObject的子节点,如果它是静态分配的话,如果没有双重删除的话。
基本上,如果我按常规方式进行,它看起来像这样:
QWidget Window(nullptr);
QPushButton button(&Window);
Window.show();
return App.exec();
//When app ends, button then Window get deleted
//because they were statically allocated
//And then, Window (should) delete button AGAIN because it's its child, thus crashing
//the program. But it doesn't. Why ?
但我也可以不崩溃地做到这一点:
and
Qt知道我是如何创建QPushButton的,还是我错过了什么?
答案 0 :(得分:8)
当QObject
被销毁时,如果它有一个,它会将其自身从父节点中删除。因此,当Window
被销毁时,它不会尝试销毁QPushButton
,因为该按钮不再位于窗口的子项列表中。
以下相关文件。它还提到如下事实:如果对象的声明顺序与父/子关系顺序不匹配,则可能确实导致对象被销毁两次。这是件坏事。