In the C++11, there are two versions of std::unordered_map::operator[], namely:
mapped_type& operator[] ( const key_type& k ); //1
mapped_type& operator[] ( key_type&& k ); //2
There are two questions:
1) Why the second one is necessary - the first one allows to pass constant to the function, since the first one contains the keyword const
2) For example, which version, 1 or 2, will be called in this case:
std::unordered_map<std::string, int> testmap;
testmap["test"] = 1;
Normally, the key is only used for comparison purposes, so you might wonder why rvalue semantics are necessary: a const reference should already cover that case.
But one thing to note is that operator[] can indeed create a new key/value pair: if the key wasn't already existent in the map.
In that case, if the second overload was used, then the map can safely move the provided key value in the map (while default initializing the value). It's a pretty rare and negligible optimization in my opinion, but when you're the C++ standard library, you shouldn't spare any efforts to save someone a cycle, even if it happens just once!
As for the second question, I might be wrong but it should consider the second overload as the best overload.
Edit: There is also a valid point that it might allow you to use move-only objects as key values, even if it's a debatable decision
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With