title: Inserting to std::unordered_map calls hash function twice in MSVC++'s STL, bad design or special reason?
body: <p>For this code:</p>
  
  <pre><code>#include&lt;unordered_map&gt;
  #include&lt;iostream&gt;
  using namespace std;
  struct myhash {
      unsigned operator()(const unsigned&amp;v)const {
          cout&lt;&lt;"Hash function is called:"&lt;&lt;v&lt;&lt;endl;
          return v;
      }
  };
  unordered_map&lt;unsigned,unsigned,myhash&gt;mp;
  int main() {
      for (unsigned i=0;i&lt;3;++i) {
          cout&lt;&lt;"Visiting hash table:"&lt;&lt;i&lt;&lt;endl;
          ++mp[i];
      }
  }
  </code></pre>
  
  <p>When using g++, there's no surprise with the output:</p>
  
  <pre><code>Visiting hash table:0
  Hash function is called:0
  Visiting hash table:1
  Hash function is called:1
  Visiting hash table:2
  Hash function is called:2
  </code></pre>
  
  <p>But the output of MSVC++(2015) shocked me:</p>
  
  <pre><code>Visiting hash table:0
  Hash function is called:0
  Hash function is called:0
  Visiting hash table:1
  Hash function is called:1
  Hash function is called:1
  Visiting hash table:2
  Hash function is called:2
  Hash function is called:2
  </code></pre>
  
  <p>Further tests showed that MSVC++'s STL calls the hash function twice when inserting a new element in the unordered_map and once if the element is already in the map.</p>
  
  <p>I feel pretty strange for this behavior because I think caching the result is much more faster than calling the hash function again under most circumstances( if the implementation really need to use the hash value twice). Or better, I think is just use the hash function once to find the bucket for the element and the following routine is not relevant to the hash value.</p>
  
  <p>However, since the authors of STL are much more experienced than me in C++, I don't know if they have some special reasons for this implementation? Is this just a bad design or caused by some reasons unknown to me?</p>