Reputation: 31
How does the dynamically allocated pointers in QT coding are destroyed because we don't write a specific destructor for them?
Upvotes: 3
Views: 1617
Reputation: 4412
To expand on Neox's answer, Qt has two methods for object management:
And the two don't really mix very well for reasons which will become apparent.
QObjects can either be 'free' or have a parent. When a QObject has its parent set (either by providing the QObject constructor with a pointer to another QObject, or by calling setParent()
) the parent QObject becomes the owner of the child QObject and will make sure any of its children are destroyed when it is. There are also several methods available to inspect child/parent relationships.
A separate method of managing dynamically allocated objects are the managed pointer classes which this paper explains quite well. To summarise though:
As you can see, some of the guarded pointer classes can be used with a QObject tree, but you should make sure you read and understand the documentation thoroughly before doing so or you may end up with a corrupt data structure.
Upvotes: 8
Reputation: 2004
The short answer is:
QObjects organize themselves in object trees. When you create a QObject with another object as parent, it's added to the parent's children() list, and is deleted when the parent is.
Qt has a good docu about object hierarchy and ownership within the framework. You can read it here
Upvotes: 3