QMap的这种用法有潜在的危害吗?

Is this use of QMap potentially harmful?

本文关键字:用法 QMap      更新时间:2023-10-16
#include <QMultiMap>
template <typename TKey, typename TValue>
TKey lastKeyOf(const QMap<TKey, TValue>& map)
{
    if (map.isEmpty())
        throw something;
    return (map.end() - 1).key();
}

我问的原因是:

template <typename TKey, typename TValue>
QMultiMap<TKey, TValue>;

公开继承QMap<TKey, TValue>。如果我调用:

QMultiMap<int, std::string> multimap;
...
lastKeyOf(multimap);

lastKeyOf内部的所有调用都静态地绑定到它们的QMap版本而不是QMultiMap版本,因为QMap不是用于多态使用(没有虚拟析构函数)。

我甚至不知道这个用法叫什么。是对象切片吗?

我相信这应该是安全的。QMultiMap只是在QMap中添加了一组新的重载方法,只有当你在lastKeyOf()中使用一个在QMultiMap中重载的具有不同行为的函数时,你才会得到意想不到的结果。我能看到的唯一具有兼容签名和不同行为的重载方法是insert()。

话虽如此,避免使用QMultiMap和QMap::insertMulti()而不是QMap::insert()来使用QMap可能会使代码更简单。