Why does std::map not have a const accessor?

C++C++11Std

C++ Problem Overview


The declaration for the [] operator on a std::map is this:

T& operator[] ( const key_type& x );

Is there a reason it isn't this?

T& operator[] ( const key_type& x );
const T& operator[] const ( const key_type& x );

Because that would be incredibly useful any time you need to access a member map in a const method.

C++ Solutions


Solution 1 - C++

As of C++11 there is std::map::at which offers const and non-const access.

In contrast to operator[] it will throw an std::out_of_range exception if the element is not in the map.

Solution 2 - C++

operator[] in a map returns the value at the specified key or creates a new value-initialized element for that key if it's not already present, so it would be impossible.

If operator[] would have a const overload, adding the element wouldn't work.

That answers the question. Alternatives:

For C++03 - you can use iterators (these are const and non-const coupled with find). In C++11 you can use the at method.

Solution 3 - C++

These answers are correct in that operator[] has semantics to add a key if it doesn't exist, but I'd like to add another perspective:

Notice how operator[] returns a T&. That is, it returns a reference to the value that is associated with key. But what if there is no key in the map? What should we return? There's no such thing as a "null-reference," and throwing an exception would be annoying.

This would be one good reason for no operator[] const. What would you return to the user if you couldn't add anything to the map (because the operator is const), but they are looking for an item that doesn't exist? A good solution to this problem is to not have the operator[] const.

Solution 4 - C++

The (non-const) operator[] creates the key if it doesn't exist.

The const version of that operator, if it existed, would have to have different semantics, since it wouldn't be able to add a new key.

I am sure you would agree that having const and non-const overloads with significantly different semantics would be a can of worms. Therefore no const version is provided.

There is a const find() member though, so you can use that in your code.

Solution 5 - C++

Because the semantics of operator[] are to add the key if it doesn't exist.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCalderView Question on Stackoverflow
Solution 1 - C++Stephan DollbergView Answer on Stackoverflow
Solution 2 - C++Luchian GrigoreView Answer on Stackoverflow
Solution 3 - C++CornstalksView Answer on Stackoverflow
Solution 4 - C++NPEView Answer on Stackoverflow
Solution 5 - C++eduffyView Answer on Stackoverflow