title: Overloading [] in C++ to return lvalue
body: <p>I'm writing a simple hash map class:</p>
  
  <pre><code>template &lt;class K, class V&gt; class HashMap;
  </code></pre>
  
  <p>The implementation is very orthodox: I have a heap array which doubles in size when it grows large. The array holds small vectors of key/value pairs.</p>
  
  <pre><code>Vector&lt;Pair&lt;K, V&gt; &gt; *buckets;
  </code></pre>
  
  <p>I would like to overload the subscript operator in such a way that code like this will work:</p>
  
  <pre><code>HashMap&lt;int, int&gt; m;
  m[0] = 10; m[0] = 20;
  m[2] = m[1] = m[0];
  </code></pre>
  
  <p>In particular,</p>
  
  <ul>
  <li>For <code>m[k] = v</code> where <code>m</code> does not contain <code>k</code>, I'd like a new entry to be added.</li>
  <li>For <code>m[k] = v</code> where <code>m</code> does contain <code>k</code>, I'd like the old value to be replaced.</li>
  <li>In both of these cases, I'd like the assignment to return <code>v</code>.</li>
  </ul>
  
  <p>Presumably the code will look something like</p>
  
  <pre><code>V&amp; operator[](K &amp;key)
  {
      if (contains(key))
      {
          // the easy case
          // return a reference to the associated value
      }
      else
      {
          Vector&lt;Pair&lt;K, V&gt; &gt; *buck = buckets + hash(k) % num_buckets;
          // unfinished
      }
  }
  </code></pre>
  
  <p>How should I handle the case where the key is not found? I would prefer to avoid copying values to the heap if I can.</p>
  
  <p>I suppose I could make a helper class which overloads both the assignment operator and a cast to <code>V</code>, but surely there is a simpler solution?</p>
  
  <p><em>Edit</em>: I didn't realize that std::map required that the value type have a zero argument constructor. I guess I will just default-construct a value as well.</p>