title: How did I manage to store a reference type in a standard container?
body: <p>While trying to work with C++11 smart pointers and container classes, I've written two pieces of code which basically boil down to the following:</p>
  
  <pre><code>class Foo { ... };
  typedef std::unique_ptr&lt;Foo&gt; FooPtr;
  
  // First attempt; this did _not_ compile
  typedef std::unordered_map&lt;int, FooPtr&gt; IntToFooMap;
  
  // Second attempt; this _did_ compile
  typedef std::unordered_map&lt;int, const FooPtr &amp;&gt; IntToFooMap;
  
  // here is the declaration causing the error in the second case:
  IntToFooMap m {
      { 41, FooPtr(new Foo()) }
  };
  </code></pre>
  
  <p>As you can see, first I tried to define an unordered map of <code>FooPtr</code>, which didn't compile, because <code>FooPtr</code> is an <code>std::unique_ptr</code> which is not copiable (it has a deleted copy constructor).</p>
  
  <p>More precisely, it is the initialization of the map using an initializer list that caused the error.</p>
  
  <p>To my great surprise, however, the second version, whereby I defined the <code>value_type</code> of the unordered map as a <strong>const reference to <code>FooPtr</code>, did compile.</strong></p>
  
  <p>Up until today, I thought that it is not possible in general to store values of reference type in standard containers. While this behavior is somewhat intuitively understandable, since declaring a (const) reference prevents the -- otherwise prohibited -- copying of the <code>unique_ptr</code>, I still don't fully understand how or why this works. <strong><em>If it works at all,</em></strong> of course; I would not be surprised if this was just a subtle corner case that resulted in undefined behavior.</p>