Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does QObject distinguish between stack and heap allocated children when deleting?

According to the Qt documentation:

QObjects organize themselves in object trees. When you create a QObject with another object as parent, the object will automatically add itself to the parent's children() list. The parent takes ownership of the object; i.e., it will automatically delete its children in its destructor.

For me that implies when a QObject is being deleted, it goes through and calls delete on all the pointers it stores in its children list.

However, it is not necessary for children to be dynamically allocated, and it is perfectly legal to build QObject trees with stack allocated objects.

According to standard specifications, calling delete on a pointer that does not point to a dynamically allocated object is undefined behavior, which may result in anything from "nothing" to a program crash.

IMO it is unlikely for QObject, which is pretty much the backbone of the almost the entire collection of Qt classes to rely on something that could produce undefined behavior.

So, does QObject distinguish between stack and heap allocated children when deleting? And if so, how exactly?

like image 539
dtech Avatar asked Sep 20 '12 13:09

dtech


1 Answers

However, it is not necessary for children to be dynamically allocated, and it is perfectly legal to build QObject trees with stack allocated objects.

No. See QObject::~QObject():

Warning: All child objects are deleted. If any of these objects are on the stack or global, sooner or later your program will crash.

like image 181
Andreas Fester Avatar answered Nov 11 '22 18:11

Andreas Fester