QCoreApplication :: postEvent的异常安全保障

时间:2014-05-15 10:03:45

标签: c++ qt qt5 exception-safety

我发布了一个包含以下代码的活动:

QEvent*event=new QEvent(QEvent::User);
QCoreApplication::postEvent(pointerToSomeQObject,event);

QCoreApplication :: postEvent被描述为here。但是,如果在postEvent中抛出异常,绝对没有关于我想要做什么的信息。

我认为该功能属于以下四个类别之一:

  1. 它永远不会抛出异常(特别是没有std :: bad_alloc)
  2. 如果它抛出则永远不会删除事件。
  3. 如果它抛出它有时会删除事件。
  4. 如果它抛出,它将始终删除事件。
  5. 最糟糕的情况是第三种情况。

    所以:如果postEvent抛出,我是否需要删除事件?

1 个答案:

答案 0 :(得分:2)

我找到了QApplication :: postEvent的代码:

void QCoreApplication::postEvent(QObject *receiver, QEvent *event, int priority)
{
    if (receiver == 0) {
        qWarning("QCoreApplication::postEvent: Unexpected null receiver");
        delete event;
        return;
    }

    QThreadData * volatile * pdata = &receiver->d_func()->threadData;
    QThreadData *data = *pdata;
    if (!data) {
        // posting during destruction? just delete the event to prevent a leak
        delete event;
        return;
    }

    // lock the post event mutex
    data->postEventList.mutex.lock();

    // if object has moved to another thread, follow it
    while (data != *pdata) {
        data->postEventList.mutex.unlock();

        data = *pdata;
        if (!data) {
            // posting during destruction? just delete the event to prevent a leak
            delete event;
            return;
        }

        data->postEventList.mutex.lock();
    }

    QMutexUnlocker locker(&data->postEventList.mutex);

    // if this is one of the compressible events, do compression
    if (receiver->d_func()->postedEvents
        && self && self->compressEvent(event, receiver, &data->postEventList)) {
        return;
    }

    if (event->type() == QEvent::DeferredDelete && data == QThreadData::current()) {
        // remember the current running eventloop for DeferredDelete
        // events posted in the receiver's thread
        static_cast<QDeferredDeleteEvent *>(event)->level = data->loopLevel;
    }

    // delete the event on exceptions to protect against memory leaks till the event is
    // properly owned in the postEventList
    QScopedPointer<QEvent> eventDeleter(event);
    data->postEventList.addEvent(QPostEvent(receiver, event, priority));
    eventDeleter.take();
    event->posted = true;
    ++receiver->d_func()->postedEvents;
    data->canWait = false;
    locker.unlock();

    QAbstractEventDispatcher* dispatcher = data->eventDispatcher.loadAcquire();
    if (dispatcher)
        dispatcher->wakeUp();
}

如果RAII QScopedPointer警卫出现异常,则需要非常小心地销毁事件。

我想我的问题的答案是第四个选择:

如果它抛出,它将始终删除给定的事件。