Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::unordered_map::operator[] - why there are two signatures?

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;
like image 943
coffee Avatar asked Jul 02 '15 14:07

coffee


1 Answers

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

like image 144
KABoissonneault Avatar answered Sep 19 '22 15:09

KABoissonneault