[英]Is this use of QMap potentially harmful?
#include <QMultiMap>
template <typename TKey, typename TValue>
TKey lastKeyOf(const QMap<TKey, TValue>& map)
{
if (map.isEmpty())
throw something;
return (map.end() - 1).key();
}
The reason I ask is that: 我问的原因是:
template <typename TKey, typename TValue>
QMultiMap<TKey, TValue>;
inherits QMap<TKey, TValue>
publicly. 公开继承QMap<TKey, TValue>
。 So if I call: 所以,如果我打电话:
QMultiMap<int, std::string> multimap;
...
lastKeyOf(multimap);
All the calls inside lastKeyOf
get statically bound to their QMap
versions instead of QMultiMap
versions, since QMap
was not intended for polymorphic use (no virtual destructor). lastKeyOf
所有调用都静态绑定到他们的QMap
版本而不是QMultiMap
版本,因为QMap
不是用于多态使用(没有虚拟析构函数)。
I am not even sure what is this use called. 我甚至不确定这个叫什么用途。 Is it object slicing? 它是对象切片吗?
I believe this should be safe. 我相信这应该是安全的。 QMultiMap just adds a new set of overloaded methods to QMap, you'll only get unexpected results if you use a function inside lastKeyOf() which is overloaded in QMultiMap to have different behavior. QMultiMap只是向QMap添加了一组新的重载方法,如果在QMultiMap中重载的lastKeyOf()中使用了一个具有不同行为的函数,则只会得到意想不到的结果。 The only overloaded method with a compatible signature and different behavior that I can see is insert(). 我能看到的唯一具有兼容签名和不同行为的重载方法是insert()。
Having said that, it may make for more straightforward code to avoid QMultiMap and use QMap only with QMap::insertMulti() instead of QMap::insert(). 话虽如此,它可以使更简单的代码避免QMultiMap并仅使用QMap :: insertMulti()而不是QMap :: insert()。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.