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
.