为什么QObject被销毁的信号被称为AFTER的销毁? [英] Why is QObject destroyed signal called AFTER the destruction?

查看:298
本文介绍了为什么QObject被销毁的信号被称为AFTER的销毁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑这个测试用例:

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();
}

它输出:

MyObject constructor
MyObject destructor
About to be destroyed!

此行为与Qt文档矛盾:此信号立即发出 / strong>对象obj被销毁,不能被阻止。

This behaviour contradicts the Qt documentation: "This signal is emitted immediately before the object obj is destroyed, and can not be blocked." Why does this happen?

推荐答案

如果你想到信号将如何发射,它是由基本的QObject做的 - 这就是QObject知道它被销毁。

If you think about how the signal would get emitted, it's done by the base QObject - that's how the QObject knows it's being destroyed.

所以当派生类被销毁时,最先导出的析构函数首先运行(每个标准C ++ dtor处理),而MyObject destructor 消息。当dtor完成时,基本dtors运行,在这种情况下,这是QObject dtor,然后发出信号和即将被销毁!显示消息。

So when the derived class is destroyed, the most derived destructor gets run first (per standard C++ dtor handling), and the "MyObject destructor" message is displayed. When that dtor completes, the base dtors get run and in this case that's the QObject dtor, which then emits the signal and the "About to be destroyed!" message is displayed.

您提到的文档中的措辞可能有点不精确。它可能更好的措辞是,这个信号是在对象obj被销毁时发出的或这个信号在对象obj被完全销毁之前立即发出。

The wording in the docs you mentioned might be a bit imprecise. It might be better worded with something like, "This signal is emitted as the object obj is destroyed" or "This signal is emitted immediately before the object obj is completely destroyed".

这篇关于为什么QObject被销毁的信号被称为AFTER的销毁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆