0

提供一些背景知识:在我的项目中,我在其中放置了一个调试断点,QMap::detach_helper因为我想看看我是否可以发现由于疏忽而导致隐式共享的 QMap 分离的任何事件,例如使用find何时constFind可以使用。我没想到会经常碰到它,因为大多数情况下我是通过 const 引用传递容器(作为旁注,显然有一个名为“clazy”的工具可以找到这些东西)。

然后我正在查看一些触发分离的内部 Qt v5.9.3 代码。堆栈跟踪显示我们正在从insertMulti此处调用的第一行函数中分离contexts

// return true if accepted (consumed)
bool QGestureManager::filterEvent(QWidget *receiver, QEvent *event)
{
    QMap<Qt::GestureType, int> types;
    QMultiMap<QObject *, Qt::GestureType> contexts;
    QWidget *w = receiver;
    typedef QMap<Qt::GestureType, Qt::GestureFlags>::const_iterator ContextIterator;
    if (!w->d_func()->gestureContext.isEmpty()) {
        for(ContextIterator it = w->d_func()->gestureContext.constBegin(),
            e = w->d_func()->gestureContext.constEnd(); it != e; ++it) {
            types.insert(it.key(), 0);
            contexts.insertMulti(w, it.key());
        }
    }
    // find all gesture contexts for the widget tree
    w = w->isWindow() ? 0 : w->parentWidget();
    while (w)
    {
        for (ContextIterator it = w->d_func()->gestureContext.constBegin(),
             e = w->d_func()->gestureContext.constEnd(); it != e; ++it) {
            if (!(it.value() & Qt::DontStartGestureOnChildren)) {
                if (!types.contains(it.key())) {
                    types.insert(it.key(), 0);
                    contexts.insertMulti(w, it.key()); // Why does this trigger a detach?
                }
            }
        }
        if (w->isWindow())
            break;
        w = w->parentWidget();
    }
    return contexts.isEmpty() ? false : filterEventThroughContexts(contexts, event);
}

为什么本地 QMultiMap contexts(从未复制过)会隐式共享并需要分离?


我的理论

这可能不相关,但contexts该行的大小为零。

我的猜测是分离是由某种与空地图相关的优化引起的,但我不确定。我确实注意到,通过将调试断点放在QMap::detach_helper仅对非空映射执行的部分(即在 conditional 内if (d->header.left)) ,我得到的命中要少得多

4

1 回答 1

0

Q(Multi)Map 不会在每次插入时分离,而只会在地图尚未初始化时分离:

QMultiMap<int, int> mm;
mm.insert(42, 43);  // detach_helper is called because the container needs to be initialized
mm.insert(43, 44);  // detach_helper is not called
于 2021-06-20T08:09:12.733 回答