I don't understand how Qt can delete all QObject's children without double deleting something if it was statically allocated.
Basically, if I do it the usual way, it looks like this :
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.
But I can also do this without crash :
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 ?
Does Qt know how I created QPushButton, or did I miss something ?
When a QObject
is destroyed, it removes itself from its parent, if it has one. Therefore when the Window
is destroyed, it doesn't try to destroy the QPushButton
, because the button is no longer in the window's list of children.
Relevant documentation below. It also mentions the fact that if the declaration order of the objects doesn't match the parent/child relationship order, it might indeed cause an object to be destroyed twice. Which is a bad thing.
http://doc.qt.io/qt-5/objecttrees.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With