Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

qt

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();
}
like image 276
Martin Drozdik Avatar asked Aug 29 '13 06:08

Martin Drozdik


1 Answers

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.

like image 102
Andrii Avatar answered Nov 06 '22 08:11

Andrii