QCoreApplication::postEvent的异常安全保证



我要发布一个事件,代码如下:

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

QCoreApplication::postEvent描述在这里。但是,如果在postEvent中抛出异常,则绝对没有关于我应该做什么的信息。

我想这个函数属于以下四类之一:

  1. 它从不抛出异常(特别是std::bad_alloc)
  2. 如果抛出,它将永远不会删除事件。
  3. 如果它抛出,它将删除事件。
  4. 如果它抛出它将总是删除事件。

最坏的情况是第三种。

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

我找到了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保护异常的情况下销毁事件是非常小心的。

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

如果它抛出它将总是删除给定的事件

相关内容

  • 没有找到相关文章

最新更新