Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Qt handle stack-allocated objects

Tags:

c++

qt

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 ?

like image 917
bisthebis Avatar asked Jul 03 '16 15:07

bisthebis


1 Answers

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

like image 165
Matti Virkkunen Avatar answered Sep 26 '22 00:09

Matti Virkkunen