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

How does Qt handle stack-allocated objects

本文关键字:堆栈 分配 对象 处理 何处理 Qt      更新时间:2023-10-16

我不明白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.

但是我也可以这样做而不会崩溃:

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 ?

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

当一个QObject被销毁时,它会从它的父级(如果它有父级)中移除自己。因此,当Window被破坏时,它不会试图破坏QPushButton,因为按钮不再在窗口的子列表中。

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

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