Why does a QObject destroy a signal called AFTER destruction?

Consider this test case:

class MyObject : public QObject { Q_OBJECT public: MyObject() { qDebug() << "MyObject constructor"; } virtual ~MyObject() { qDebug() << "MyObject destructor"; } }; class Tracker : public QObject { Q_OBJECT public: Tracker() {} public slots: void onDestructor() { qDebug() << "About to be destroyed!"; } }; int main(int argc, char** argv) { QCoreApplication app(argc, argv); Tracker tracker; MyObject *obj = new MyObject(); QObject::connect(obj, SIGNAL(destroyed()), &tracker, SLOT(onDestructor())); delete obj; return app.exec(); } 

He prints this:

 MyObject constructor MyObject destructor About to be destroyed! 

This behavior contradicts the Qt documentation: "This signal is immediately issued before , the obj object is destroyed and cannot be blocked." Why is this happening?

+6
source share
1 answer

If you think about how the signal will be emitted, this is done by the basic QObject - by the way the QObject knows that it has been destroyed.

Thus, when the derived class is destroyed, the most derived destructor is launched first (for standard C ++ dtor data processing), and the message "MyObject destructor" displayed. When this dtor completes, the underlying dtors start, and in this case a QObject dtor is displayed, which then emits a signal and the message "About to be destroyed!" .

The wording in the mentioned documents may be a little inaccurate. It can be better worded with something like: "This signal is emitted when obj is destroyed" or "This signal is emitted just before obj is completely destroyed."

+16
source

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


All Articles