]> git.ipfire.org Git - thirdparty/gcc.git/commitdiff
libstdc++: Fix incorrect move in flat_map::_M_try_emplace [PR125374]
authorPatrick Palka <ppalka@redhat.com>
Tue, 19 May 2026 17:43:10 +0000 (13:43 -0400)
committerPatrick Palka <ppalka@redhat.com>
Tue, 19 May 2026 17:43:10 +0000 (13:43 -0400)
PR libstdc++/125374

libstdc++-v3/ChangeLog:

* include/std/flat_map (_Flat_map_impl::_M_try_emplace): Forward
instead of unconditionally moving __k when inserting it.
* testsuite/23_containers/flat_map/1.cc (test10): New test.

Reviewed-by: Jonathan Wakely <jwakely@redhat.com>
libstdc++-v3/include/std/flat_map
libstdc++-v3/testsuite/23_containers/flat_map/1.cc

index e270735a87bad1899933c6d0297985c994e39419..18f06e6bdaf81fdfb078f8356b135a4a3c676349 100644 (file)
@@ -534,7 +534,7 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
              return {iterator{this, __key_it}, false};
 
          auto __guard = _M_make_clear_guard();
-         __key_it = _M_cont.keys.insert(__key_it, std::move(__k));
+         __key_it = _M_cont.keys.insert(__key_it, std::forward<_Key2>(__k));
          __value_it = _M_cont.values.begin() + (__key_it - _M_cont.keys.begin());
          _M_cont.values.emplace(__value_it, std::forward<_Args>(__args)...);
          __guard._M_disable();
index 04c2101aab13c8c2181a505e51390ddfb69ce55e..096b9eeac3e44a75591b42f0929e4ddf05555825 100644 (file)
@@ -13,6 +13,7 @@
 #include <testsuite_allocator.h>
 #include <testsuite_hooks.h>
 #include <testsuite_iterators.h>
+#include <string>
 #include <tuple>
 
 struct Gt {
@@ -283,6 +284,21 @@ test09()
   using value_type = std::pair<int, int>;
 }
 
+constexpr
+void
+test10()
+{
+  // PR libstdc++/125374 - flat_map unconditionally moves from lvalue keys in
+  // _M_try_emplace
+  std::flat_map<std::string, int, std::less<>> m;
+  std::string k = "hello";
+  m[k] = 1;
+  VERIFY (k == "hello");
+  k = "world";
+  m.try_emplace(k, 2);
+  VERIFY (k == "world");
+}
+
 void
 test()
 {
@@ -298,6 +314,7 @@ test()
   test07();
   test08();
   test09();
+  test10();
 }
 
 constexpr
@@ -313,6 +330,7 @@ test_constexpr()
   test07();
   test08();
   test09();
+  test10();
   return true;
 }