为什么要将 `QThread::finished` 信号连接到 `QObject::deleteLater`?
Why connect `QThread::finished` signal to `QObject::deleteLater`?
我在 QThread::finished
的 Qt 5.15 文档中读到了这个:
When this signal is emitted, the event loop has already stopped running. No more events will be processed in the thread, except for deferred deletion events. This signal can be connected to QObject::deleteLater()
, to free objects in that thread.
但是,在文档的 another section 中,它说
Calling delete
on a QObject from a thread other than the one that owns the object (or accessing the object in other ways) is unsafe, unless you guarantee that the object isn't processing events at that moment [emphasis mine].
如果我理解正确,在发出 QThread::finished
之后,事件循环已经停止 运行,并且如果不存在延迟删除事件(即 QObject::deleteLater
没有' t been called),线程中的所有对象也应该已经完成了事件处理。那么为什么要为这些对象使用 QObject::deleteLater
而不是手动删除它们呢?我使用 QObject::deleteLater
没问题;我只是想确保我对 Qt 的理解是正确的。
QObject::deleteLater
在这种情况下本质上只是在谨慎方面犯了错误。如果您绝对确定对象不会被访问,那么您没有理由不简单地 delete
对象。
实际上,与在运行时或退出时调试一些看似随机的崩溃的麻烦相比,使用 QObject::deleteLater
并让 Qt 为您处理它会节省更多时间,因为有恰好是对您手动删除的对象的访问。
我在 QThread::finished
的 Qt 5.15 文档中读到了这个:
When this signal is emitted, the event loop has already stopped running. No more events will be processed in the thread, except for deferred deletion events. This signal can be connected to
QObject::deleteLater()
, to free objects in that thread.
但是,在文档的 another section 中,它说
Calling
delete
on a QObject from a thread other than the one that owns the object (or accessing the object in other ways) is unsafe, unless you guarantee that the object isn't processing events at that moment [emphasis mine].
如果我理解正确,在发出 QThread::finished
之后,事件循环已经停止 运行,并且如果不存在延迟删除事件(即 QObject::deleteLater
没有' t been called),线程中的所有对象也应该已经完成了事件处理。那么为什么要为这些对象使用 QObject::deleteLater
而不是手动删除它们呢?我使用 QObject::deleteLater
没问题;我只是想确保我对 Qt 的理解是正确的。
QObject::deleteLater
在这种情况下本质上只是在谨慎方面犯了错误。如果您绝对确定对象不会被访问,那么您没有理由不简单地 delete
对象。
实际上,与在运行时或退出时调试一些看似随机的崩溃的麻烦相比,使用 QObject::deleteLater
并让 Qt 为您处理它会节省更多时间,因为有恰好是对您手动删除的对象的访问。