QMap operator [] return value
-
Hello. This is how the [] operator is overloaded in QMap:
@ T & operator[](const Key & key)
const T operator[](const Key & key) const@What I think is that the const version should return a reference to T, just like the non-const version does. (And like other Qt container classes like QList and QVector do). After getting used to the way this operator behaves in other container classes, I just expected it to work the same way in QMap and it took me hours and hours to find where my problem was. Right now i'm trying to solve it and I see there's just no way to get a const reference to T. I'm calling this from a const reference to a QMap, so I cannot get a non-const reference also. I think this is a real problem but, hey, I'm no expert. What do you guys think?
-
The reason is given (indirectly) in the "documentation":http://qt-project.org/doc/qt-5.1/qtcore/qmap.html:
"const T QMap::value(const Key & key, const T & defaultValue = T()) const
If the map contains no item with key key, the function returns defaultValue. If no defaultValue is specified, the function returns a default-constructed value."It cannot return a const reference to a default-constructed value, because that value will be destroyed when the function returns. Thus, it must return a copy. (In contrast, the non-const version can just insert the default-constructed value into the map, then return a reference to the stored value)
If this is a problem for you because you are storing large data structures, you can store pointers instead.
-
Now I understand. Thank you!
I see c++ standard library had the same problem, but it was solved in c++11. The [] operator behaves just like the one in Qt, but they have created a new function, called at:
@ mapped_type& at (const key_type& k);
const mapped_type& at (const key_type& k) const;@If the key k does not match any element, it just throws an exception.
I think it would be a good idea to add this to QMap, don't you think?
-
Yes, it would be nice to have a way to get a const reference from a QMap. Please post your suggestion to https://bugreports.qt-project.org/ if you wish.
Note that with STL containers, operator doesn't perform bounds checking, while at() does; in Qt, neither operator nor at() perform bounds checking. So, for consistency, the new function for QMap would have to be called something other than at().