为什么QMap :: operator [](const Key& key)按值返回? [英] Why does QMap::operator[](const Key & key) return by value?
本文介绍了为什么QMap :: operator [](const Key& key)按值返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我注意到 QMap :: operator [](const Key& key)
具有这两个超载:
T & QMap::operator[](const Key & key)
const T QMap::operator[](const Key & key) const
是否有按价值返回的原因?
由于我们具有移动语义:
And since we have move semantics:
按值返回时,是否应该按常量值返回?
我问的原因是:
想象我们有:
class ExpensiveToCopy;
{
public:
int someProperty() const;
...
}
void f(const QMap<int, ExpensiveToCopy>& map)
{
int lala = map[4].someProperty(); // We need to copy the entire object
// just to look at someProperty();
}
推荐答案
在<$ c在$ c> const 的情况下,我们不能将元素添加到 const
映射(如果尚不存在),则将返回本地对象。
In the the const
case we can not add an element to the const
map if it does not already exist, so a local object will be returned.
否则,在非 const
情况下,将使用指定的键创建一个元素(如果没有)还没有一个),然后返回对其的引用。
Otherwise, in the non-const
case, an element will be created with the specified key (if there isn't one already) before returning a reference to it.
这篇关于为什么QMap :: operator [](const Key& key)按值返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文