[SOLVED] Does QObject distinguish between stack and heap allocated children?
QObject is responsible for managing the lifetime of its children. However, not all children are dynamically allocated, even thou it is recommended practice to use pointers and dynamic allocation it is also possible to use stack allocation and still pass a QObject or derived class to parent to.
So is there a way for QObject to distinguish and delete only the children that are dynamically allocated and leave the lifetime management of stack objects to their respective scopes?
twsimpson last edited by
No, it doesn't know if an object was allocated on the stack or the heap, so you need to be careful, though it usually doesn't matter:
When the scope these were defined in ends, then each object is destroyed in reverse order, so obj3 is first destroyed, and is removed from obj2's children list. Then obj2 is destroyed and removed from obj's children list. Finally obj is destroyed, but as it now has no children, it doesn't attempt to free any of the already destroyed objects.
I am asking because according to the specification, calling delete on a pointer that has not been used to allocate an object with new is undefined behavior. In other words, it may or may not work, and indeed as I tested it I sometimes got crashes sometimes everything was working just fine.
Surely, QObject child lifetime management cannot rely on undefined behavior?
andre last edited by
In the example by Terence, there is no undefined behaviour, as the Qt mechanism does not come into effect. I am not saying it is impossible to construct one though. Could you show an example where you think it breaks down?
I haven't produced anything that breaks down, I am just curious of how is eventual issue being prevented, if it is at all. Having children "divorce" from their parents on deletion should take care of such cases.
Thanks for the responses, I see you answered that question in SO as well, couldn't ask for more.
Basically, the whole mechanism relies on the fact parent-child connection is two way, not only parents know their children but children know their parents too. I was implementing a more economic scheme where the connection is one way, so there is really no way of taking care of stack allocated objects as well as eventual dangling pointers.
tobias.hunger last edited by
This is what the documentation of "QObject::~QObject":http://qt-project.org/doc/qt-4.8/qobject.html says:
bq. Warning: All child objects are deleted. If any of these objects are on the stack or global, sooner or later your program will crash.