Qt如何处理堆栈分配的对象

bis*_*bis 4 c++ qt

我不明白Qt如何删除所有QObject的子节点,如果它是静态分配的话,如果没有双重删除.

基本上,如果我按常规方式执行,它看起来像这样:

QWidget Window(nullptr);
QPushButton* button = new QPushButton(&Window);
Window.show();
return App.exec(); 
//When app ends, Window gets deleted 
//because it was statically allocated
//And then, Window deletes button because it's its child.
Run Code Online (Sandbox Code Playgroud)

但我也可以不崩溃地做到这一点:

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 ?
Run Code Online (Sandbox Code Playgroud)

Qt知道我是如何创建QPushButton的,还是我错过了什么?

Mat*_*nen 8

当a QObject被销毁时,它会从父节点中删除它(如果有的话).因此当Window被破坏时,它不会试图破坏QPushButton,因为按钮不再在窗口的子列表中.

以下相关文件.它还提到如下事实:如果对象的声明顺序与父/子关系顺序不匹配,则可能确实导致对象被销毁两次.这是件坏事.

http://doc.qt.io/qt-5/objecttrees.html