Loading

Qt源码阅读(五)-deleteLater

Qt deleteLater作用及源码分析

个人经验总结,如有错误或遗漏,欢迎各位大佬指正 🥳

在本篇文章中,我们将深入分析源码,探讨deleteLater的原理。

deleteLater是Qt框架提供的一个重要函数,用于在事件循环中延迟删除对象。

在软件开发中,延迟删除对象的概念是非常重要的,特别是当对象不再被需要,但由于某些原因(比如对象正在被访问、事件循环中仍有关于该对象的事件等),不能立即删除。deleteLater函数提供了一种机制,可以将对象的删除操作延迟执行,从而避免了可能的悬空指针和资源泄漏问题。

在本文中,我们将深入研究源码,揭示deleteLater函数的工作原理。我们将分析QCoreApplicationpostEvent函数以及QObjectevent函数,并解释它们如何协同工作来实现延迟删除的效果。

通过深入分析源码并理解deleteLater的内部工作原理,我们将更好地了解它在Qt框架中的作用和优势。

deleteLater的作用

根据官方文档中的解释:

Schedules this object for deletion.

The object will be deleted when control returns to the event loop. If the event loop is not running when this function is called (e.g. deleteLater() is called on an object before QCoreApplication::exec()), the object will be deleted once the event loop is started. If deleteLater() is called after the main event loop has stopped, the object will not be deleted. Since Qt 4.8, if deleteLater() is called on an object that lives in a thread with no running event loop, the object will be destroyed when the thread finishes.

Note that entering and leaving a new event loop (e.g., by opening a modal dialog) will not perform the deferred deletion; for the object to be deleted, the control must return to the event loop from which deleteLater() was called. This does not apply to objects deleted while a previous, nested event loop was still running: the Qt event loop will delete those objects as soon as the new nested event loop starts.

计划删除一个对象。

当控制返回到事件循环时,对象将被删除。如果在调用此函数时事件循环没有运行(例如,在QCoreApplication::exec()之前在对象上调用deleteLater()),则一旦事件循环启动,该对象将被删除。如果在主事件循环停止后调用deleteLater(),则不会删除对象。自Qt 4.8以来,如果deleteLater()在没有运行事件循环的线程中的对象上调用,则该对象将在线程结束时被销毁。

注意,进入和离开一个新的事件循环(例如,通过打开一个模态对话框)不会执行延迟删除;对于要删除的对象,必须返回到从中调用deleteLater()的事件循环。这不适用于在以前的嵌套事件循环仍在运行时删除的对象:Qt事件循环将在新的嵌套事件循环开始时删除这些对象。

🙋‍♂️那为什么需要把这样一个删除动作丢到事件循环去呢?

因为也许在执行删除某个QObject对象的操作时,事件队列中仍然有关于这个QObject对象的事件,如果直接删除该对象,就会导致后面调用这个对象时,引起程序的崩溃。也就是解决悬空指针的问题。

源码分析

首先,我们先看deleteLater做了些什么操作:

void QObject::deleteLater()
{
    QCoreApplication::postEvent(this, new QDeferredDeleteEvent());
}

可以看到,deleteLater函数中,仅仅只是往事件队列中添加了一个DeferedDelete事件。

其次,我们再看QObject的事件处理函数——event

bool QObject::event(QEvent *e)
{
    switch (e->type()) {
 	// ...

    case QEvent::DeferredDelete:
        qDeleteInEventHandler(this);
        break;
            
	// ...
}
void qDeleteInEventHandler(QObject *o)
{
    delete o;
}

从上面,我们可以看到,deleteLater发出来的事件,最后处理的时候,就是简简单单的调用delete进行析构。也就能印证deleteLater的作用:

计划删除一个对象。当控制返回到事件循环时,对象将被删除

但作为一位技术人,看到官方文档中,对这个函数有一段这么长的描述,总觉得事情是不是有点太简单了,难道是我打开的方式不对?抱着这个想法,我又看了一遍源码,也算是找到了一些另外的处理。

再探源码

这次,我从deleteLater中发送事件(postEvent)下手,看是不是这个里面有着特殊处理:

void QCoreApplication::postEvent(QObject *receiver, QEvent *event, int priority)
{
    // ...

    if (event->type() == QEvent::DeferredDelete && data == QThreadData::current()) {
        // remember the current running eventloop for DeferredDelete
        // events posted in the receiver's thread.

        // Events sent by non-Qt event handlers (such as glib) may not
        // have the scopeLevel set correctly. The scope level makes sure that
        // code like this:
        //     foo->deleteLater();
        //     qApp->processEvents(); // without passing QEvent::DeferredDelete
        // will not cause "foo" to be deleted before returning to the event loop.

        // If the scope level is 0 while loopLevel != 0, we are called from a
        // non-conformant code path, and our best guess is that the scope level
        // should be 1. (Loop level 0 is special: it means that no event loops
        // are running.)
        int loopLevel = data->loopLevel;
        int scopeLevel = data->scopeLevel;
        if (scopeLevel == 0 && loopLevel != 0)
            scopeLevel = 1;
        static_cast<QDeferredDeleteEvent *>(event)->level = loopLevel + scopeLevel;
    }
    // ...
}

在这里面,把这个DeferedDelete事件中的循环级别设置了一下,以便待会进行事件发送的时候,能够进行当前事件是否要处理的判断。

void QCoreApplicationPrivate::sendPostedEvents(QObject *receiver, int event_type,
                                               QThreadData *data)
{
        // ...

        if (pe.event->type() == QEvent::DeferredDelete) {
            // DeferredDelete events are sent either
            // 1) when the event loop that posted the event has returned; or
            // 2) if explicitly requested (with QEvent::DeferredDelete) for
            //    events posted by the current event loop; or
            // 3) if the event was posted before the outermost event loop.

            int eventLevel = static_cast<QDeferredDeleteEvent *>(pe.event)->loopLevel();
            int loopLevel = data->loopLevel + data->scopeLevel;
            const bool allowDeferredDelete =
                (eventLevel > loopLevel
                 || (!eventLevel && loopLevel > 0)
                 || (event_type == QEvent::DeferredDelete
                     && eventLevel == loopLevel));
            if (!allowDeferredDelete) {
                // cannot send deferred delete
                if (!event_type && !receiver) {
                    // we must copy it first; we want to re-post the event
                    // with the event pointer intact, but we can't delay
                    // nulling the event ptr until after re-posting, as
                    // addEvent may invalidate pe.
                    QPostEvent pe_copy = pe;

                    // null out the event so if sendPostedEvents recurses, it
                    // will ignore this one, as it's been re-posted.
                    const_cast<QPostEvent &>(pe).event = nullptr;

                    // re-post the copied event so it isn't lost
                    data->postEventList.addEvent(pe_copy);
                }
                continue;
            }
        }

        // ...
}

上面代码中,我们可以看到判断当前是否允许处理DeferredDelete事件时,有三个条件,也就是上面注释所说的:

  1. 当发布事件的事件循环返回时
  2. 事件在最外层的事件循环之前调用
  3. 显示的调用QEvent::DeferredDelete事件
const bool allowDeferredDelete =
                (eventLevel > loopLevel
                 || (!eventLevel && loopLevel > 0)
                 || (event_type == QEvent::DeferredDelete
                     && eventLevel == loopLevel));

如果DeferredDelete不能在当前的循环中被处理,那么将事件重新封装,重新添加到线程的事件列表中,等待能够处理该事件的事件循环去处理。

使用提示

通过上面的分析,调用deleteLater会延迟删除一个QObject对象,并最终妥善的删除。但是,在我们使用的过程中,仍然是要注意,将原指针置nullptr的,不然就会导致野指针了。

那么,我们应该在什么时候去进行置空处理呢

Qt官方文档中有做解释:

[signal] void QObject::destroyed(QObject *obj = nullptr)

This signal is emitted immediately before the object obj is destroyed, after any instances of QPointer have been notified, and cannot be blocked.
All the objects's children are destroyed immediately after this signal is emitted

在一个QObject对象析构时,会发射一个信号——destroyed。使用方法如下:

QObject* obj = new QObject();

connect(obj, &QObject::destroyed, [&] () { obj = nullptr; });

obj->deleteLater();

总结

  1. deleteLater为Qt提供了一个方便且安全的方式来延迟删除对象,避免了悬挂指针和资源泄漏的问题。它提供了一种简化代码的机制,在特定情况下非常有用。
  2. 相较于手动删除和直接调用delete,deleteLater为延迟删除对象提供了一种更加简介和安全的方式。手动删除需要开发人员自己管理对象的生命周期,而deleteLater则通过将删除请求加入到事件队列,实现了自动化的延迟删除。
  3. deleteLater适用于需要延迟删除对象的场景,特别是在槽函数中需要删除与信号关联的对象时。

💕 创作不易,如果本篇博客对您有帮助,麻烦点赞、收藏、关注支持一下😉

posted @ 2023-07-09 21:31  师从名剑山  阅读(824)  评论(0编辑  收藏  举报