title: Safety of std::unordered_map::merge()
body: <p>While writing some code targeting C++17, I kind of hit a stumbling block determining the exception-safety of an operation merging two compatible std::unordered_maps. Per the current <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/n4659.pdf" rel="noreferrer">working draft</a>, §26.2.7, table 91 reads, in part, regarding the conditions of <code>a.merge( a2 )</code>:</p>
  <blockquote>
  <p><em>Requires:</em> <code>a.get_allocator() == a2.get_allocator()</code>.</p>
  <p>Attempts to extract each element in <code>a2</code> and insert it into <code>a</code> using the hash function and key equality predicate of <code>a</code>. In containers with unique keys, if there is an element in <code>a</code> with key equivalent to the key of an element from <code>a2</code>, then that element is not extracted from <code>a2</code>.</p>
  <p><em>Postconditions:</em> Pointers and references to the transferred elements of <code>a2</code> refer to those same elements but as members of <code>a</code>. Iterators referring to the transferred elements and all iterators referring to <code>a</code> will be invalidated, but iterators to elements remaining in <code>a2</code> will remain valid.</p>
  <p><em>Throws:</em> Nothing unless the hash function or key equality predicate throws.</p>
  </blockquote>
  <p>It's worth noting that these conditions are strongly reminiscent of those given for the requirements of ordinary associative containers (std::map), given in §26.2.6, table 90, <code>a.merge( a2 )</code>:</p>
  <blockquote>
  <p><em>Requires:</em> <code>a.get_allocator() == a2.get_allocator()</code>.</p>
  <p>Attempts to extract each element in <code>a2</code> and insert it into <code>a</code> using the comparison object of <code>a</code>. In containers with unique keys, if there is an element in <code>a</code> with key equivalent to the key of an element from <code>a2</code>, then that element is not extracted from <code>a2</code>.</p>
  <p><em>Postconditions:</em> Pointers and references to the transferred elements of <code>a2</code> refer to those same elements but as members of <code>a</code>. Iterators referring to the transferred elements will continue to refer to their elements, but they now behave as iterators into <code>a</code>, not into <code>a2</code>.</p>
  <p><em>Throws:</em> Nothing unless the comparison object throws.</p>
  </blockquote>
  <p>I needed to merge two std::unordered_maps with the same number of elements which I could ensure would be unique across both containers, meaning that the map containing the merged result would have double the number of elements it previously had, and the container merged-from would be empty. This should be perfectly safe thanks to C++17, right?</p>
  <p>This is a huge win in terms of performance… except, I had this nagging doubt. Hilariously, the postcondition statement says nothing about whether or not the previous max load factor in the merged map would be honored, and while that seems like a safe implicit assumption, it seemed to naïvely conflict with the statement about the unordered_map's exception-safety. If you're using a hash table design wherein the buckets are contiguously allocated buffers, maintaining your load factor would seem to imply rehashing, which would seem to imply reallocation of the bucket buffer.</p>
  <p>Already, this seemed like an exercise in extreme navel-gazing and there was good cause to leave well enough alone: a more complicated hash table could conceivably be made as a completely node-based structure, similar to the red-black trees usually underpinning std::map, and in such a case, the spec seemed reasonable as a rehash wouldn't imply allocation.</p>
  <p>Perhaps to my benefit, I succumbed to doubt and dug into gcc-7.1's implementation of merge. It's incredibly complicated, but to summarize my findings, I found that the buckets are, indeed, contiguously allocated buffers, and rehashing does imply reallocation. Maybe, I thought, there was some deeper magic I was missing (I stared at the source for nearly an entire day and still felt I had a poor understanding of it) which just disabled rehashing during a merge, meaning that all of the specified conditions would be upheld, but you could get a nasty performance regression after a suitably large merge, since your map would likely be overloaded.</p>
  <p>I moved for a practical assessment mirroring my use-case (which I would have presented if it were possible, I'm sorry), instead of just questioning my interpretation of libstdc++:</p>
  <pre><code>#include &lt;memory&gt;        // for std::shared_ptr&lt;&gt;
  #include &lt;new&gt;           // for std::bad_alloc
  #include &lt;utility&gt;       // for std::move(), std::pair&lt;&gt;
  #include &lt;type_traits&gt;   // for std::true_type
  #include &lt;unordered_map&gt; // for std::unordered_map&lt;&gt;
  #include &lt;functional&gt;    // for std::hash&lt;&gt;, std::equal_to&lt;&gt;
  #include &lt;string&gt;        // for std::string
  #include &lt;iostream&gt;      // for std::cout
  #include &lt;cstddef&gt;       // for std::size_t
  
  template&lt;typename T&gt;
  class PrimedFailureAlloc
  {
  public:
    using value_type = T;
    using propagate_on_container_copy_assignment = std::true_type;
    using propagate_on_container_move_assignment = std::true_type;
    using propagate_on_container_swap = std::true_type;
  
    PrimedFailureAlloc() = default;
  
    template&lt;typename U&gt;
    PrimedFailureAlloc( const PrimedFailureAlloc&lt;U&gt;&amp; source ) noexcept
      : m_triggered{ source.m_triggered }
    { }
  
    template&lt;typename U&gt;
    PrimedFailureAlloc( PrimedFailureAlloc&lt;U&gt;&amp;&amp; source ) noexcept
      : m_triggered{ std::move( source.m_triggered ) }
    { }
  
    T* allocate( std::size_t n )
    {
      if ( *m_triggered ) throw std::bad_alloc{};
      return static_cast&lt;T*&gt;( ::operator new( sizeof( T ) * n ) );
    }
  
    void deallocate( T* ptr, std::size_t n ) noexcept
    {
      ::operator delete( ptr );
    }
  
    bool operator==( const PrimedFailureAlloc&amp; rhs ) noexcept
    {
      return m_triggered == rhs.m_triggered;
    }
  
    void trigger() noexcept { *m_triggered = true; }
  
  private:
    template&lt;typename U&gt;
    friend class PrimedFailureAlloc;
  
    std::shared_ptr&lt;bool&gt; m_triggered{ new bool{ false } };
  };
  
  template&lt;typename T&gt;
  bool operator!=( const PrimedFailureAlloc&lt;T&gt;&amp; lhs,
                   const PrimedFailureAlloc&lt;T&gt;&amp; rhs ) noexcept
  {
    return !(lhs == rhs);
  }
  
  template&lt; typename Key
          , typename T
          , typename Hash = std::hash&lt;Key&gt;
          , typename KeyEqual = std::equal_to&lt;Key&gt;
          &gt;
  using FailingMap = std::unordered_map&lt;
    Key,
    T,
    Hash,
    KeyEqual,
    PrimedFailureAlloc&lt;std::pair&lt;const Key, T&gt;&gt;
  &gt;;
  
  template&lt;typename Key, typename T&gt;
  void printMap( const FailingMap&lt;Key, T&gt;&amp; map )
  {
    std::cout &lt;&lt; &quot;{\n&quot;;
    for ( const auto&amp; [str, index] : map )
      std::cout &lt;&lt; &quot;  { &quot; &lt;&lt; str &lt;&lt; &quot;, &quot; &lt;&lt; index &lt;&lt; &quot; }\n&quot;;
    std::cout &lt;&lt; &quot;}\n&quot;;
  }
  
  int main()
  {
    PrimedFailureAlloc&lt;std::pair&lt;const std::string, int&gt;&gt; a;
    FailingMap&lt;std::string, int&gt; m1{ a };
    FailingMap&lt;std::string, int&gt; m2{ a };
  
    m1.insert( { { &quot;Purple&quot;, 0 }, { &quot;Green&quot;, 3 }, { &quot;Indigo&quot;, 16 } } );
    m2.insert( { { &quot;Blue&quot;, 12 }, { &quot;Red&quot;, 2 }, { &quot;Violet&quot;, 5 } } );
  
    // m1.reserve( m1.size() + m2.size() );
    a.trigger();
    m1.merge( m2 );
  
    std::cout &lt;&lt; &quot;map :=\n&quot;;
    printMap( m1 );
  
    return 0;
  }
  </code></pre>
  <p>Sure enough, after compiling this code under GCC-7.1, I get:</p>
  <pre><code>terminate called after throwing an instance of 'std::bad_alloc'
    what():  std::bad_alloc
  [1]    10944 abort      ./a.out
  </code></pre>
  <p>Whereas, uncommenting line 95 (<code>m1.reserve( m1.size() + m2.size() );</code>), results in the expected output:</p>
  <pre><code>map :=
  {
    { Red, 2 }
    { Violet, 5 }
    { Purple, 0 }
    { Green, 3 }
    { Blue, 12 }
    { Indigo, 16 }
  }
  </code></pre>
  <p>Understanding that C++17 is still a draft standard which hasn't yet been finalized, and that gcc's implementation is experimental, I suppose my question would be:</p>
  <ol>
  <li>Have I gravely misconstrued the safety of the merge operation as set out in the standard? Are there best-practices to using <code>std::unordered_map::merge()</code> that I've missed? Was I supposed to be implicitly responsible for ensuring the allocation of buckets? Will using <code>std::unordered_map::reserve()</code> actually be portable when clang, MSVC, and Intel finally support C++17? I mean, my program aborting when an exception-free merge was impossible does, after some notion, adhere to the listed postconditions…</li>
  <li>Is this actually a defect in the standard? The similarity of the wording between unordered associative containers and ordinary associative containers might have allowed unintended guarantees to slip in if the text were, say, copy-pasted.</li>
  <li>Is this just a gcc bug?</li>
  </ol>
  <p>It's worth noting that I did check gcc's bug tracker prior to this write-up and seemed to find no open bugs matching my description, and furthermore, I checked the C++ standard defect report and similarly seemed to have come up empty (admittedly, doing a text-search of that site is aggravating and I may have been less than thorough). The latter is unsurprising, since standard defects and their workarounds or consequences are usually noted in gcc's source code and I found no such notations during my examination. I tried compiling my example code in my most recent checkout of clang (over a week old), but the compiler segfaulted so I took my examination there no further, and have not consulted libc++.</p>