user1162272
user1162272

Reputation: 31

Dynamic memory Deallocation in QT

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

Answers (2)

Samuel Harmer
Samuel Harmer

Reputation: 4412

To expand on Neox's answer, Qt has two methods for object management:

  1. QObject tree structure
  2. Managed pointer classes

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:

  • "The QScopedPointer class stores a pointer to a dynamically allocated object, and deletes it upon destruction" and is therefore good when you need objects which have clear and obvious ownership and lifetime.
  • "The QSharedPointer class holds a strong reference to a shared pointer [and] will delete the pointer it is holding when it goes out of scope, provided no other QSharedPointer objects are referencing it" and is therefore good when ownership is not as clear cut, but you want to make sure it doesn't get lost and become a memory leak. QWeakPointer can be used to share the pointer without implying any ownership.

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

Neox
Neox

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

Related Questions