Defining a native destructor, although the class is derived from QObject?

Let it have a class Test and a class AnotherClass . Both come from QObject.

test.h:

 class Test : public QObject { Q_OBJECT public: Test(QObject* parent); ~Test(); private: AnotherClass* other; }; class AnotherClass : public QObject { Q_OBJECT public: AnotherClass(QObject* parent); ~AnotherClass(); }; 

test.cpp:

 Test::Test(QObject* parent) : QObject(parent) { other = new AnotherClass(this); } Test::~Test() { delete other; } 

other should be automatically destroyed when the Test -instance object is destroyed, since Test is the parent of other , right?

  • Now should I delete other own in ~Test() or leave the program at undefined because it is trying to delete the same object twice?
  • What is the right approach?
+5
source share
2 answers

QObjects are organized in object trees. When you create a QObject with another object as a parent, the object will automatically add itself to the children () parent list. The parent takes responsibility for the object; that is, it automatically removes its children in its destructor. See Trees and Property for more details.

Since you pass this pointer to the Test object in the constructor of AnotherClass, this means that you are using the test object as the parent of AnotherClass. Thus, deleting the Test object also removes its child and you do not need to explicitly delete the other.

However, in this case, explicit deletion in the destructor does not cause double deletion, since it causes deregistration from the children () parent list.

+10
source

In addition to what you need to do a virtual destructor, the Qt documentation says:

When a QObject created on the heap (i.e. created using new ), the tree can be built from them in any order, and then the objects in the tree can be destroyed in any order. When any QObject in the tree is deleted, if the object has a parent, the destructor automatically removes the object from its parent. If the object has children, the Destructor automatically deletes each child. No QObject is deleted twice, regardless of the destruction order.

So you can delete the other class explicitly, but you don't need this. Any approach should work without double delete s.

By the way, you can also make AnotherClass simple Test member instead of a pointer.

+4
source

Source: https://habr.com/ru/post/1240602/


All Articles