gpt4 book ai didi

c++ - QMap::operator[](const Key & key) 为什么按值返回?

转载 作者:可可西里 更新时间:2023-11-01 16:35:40 26 4
gpt4 key购买 nike

我注意到 QMap::operator[](const Key & key) 有这两个 overloads :

    T & QMap::operator[](const Key & key)
const T QMap::operator[](const Key & key) const

有按值返回的理由吗?

因为我们有移动语义:

按值返回时,我们应该按常量值返回吗?

我问的原因是:

假设我们有:

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();
}

最佳答案

const 的情况下,如果元素不存在,我们不能将元素添加到 const 映射中,因此将返回一个本地对象。

否则,在非 const 情况下,将使用指定的键(如果还没有)创建一个元素,然后返回对它的引用。

关于c++ - QMap::operator[](const Key & key) 为什么按值返回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18503700/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com