Why does QMap::operator[](const Key & key) return by value?

c++, c++11, qt

Solution

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.

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.

Problem

I noticed that the `QMap::operator[](const Key & key)` has these two overloads: ``` T & QMap::operator[](const Key & key) const T QMap::operator[](const Key & key) const ``` Is there a reason for returning by value? And since we have move semantics: when returning by value, should we ever return by const value? The reason why I am asking is this: Imagine we have: ``` 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(); } ```

Original source

Related problems