Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic memory Deallocation in QT

Tags:

c++

qt

How does the dynamically allocated pointers in QT coding are destroyed because we don't write a specific destructor for them?

like image 505
user1162272 Avatar asked Jan 26 '26 12:01

user1162272


1 Answers

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.

like image 162
Samuel Harmer Avatar answered Jan 29 '26 04:01

Samuel Harmer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!