https://gcc.gnu.org/g:f7e3e2881412f1f80bdeb8303ab20fc8f84dda3e

commit r16-8949-gf7e3e2881412f1f80bdeb8303ab20fc8f84dda3e
Author: Patrick Palka <[email protected]>
Date:   Tue May 19 13:43:10 2026 -0400

    libstdc++: Fix incorrect move in flat_map::_M_try_emplace [PR125374]
    
            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 <[email protected]>
    (cherry picked from commit 6d114645fa1c9831a109c8a8934685f49364818a)

Diff:
---
 libstdc++-v3/include/std/flat_map                  |  2 +-
 libstdc++-v3/testsuite/23_containers/flat_map/1.cc | 18 ++++++++++++++++++
 2 files changed, 19 insertions(+), 1 deletion(-)

diff --git a/libstdc++-v3/include/std/flat_map 
b/libstdc++-v3/include/std/flat_map
index e270735a87ba..18f06e6bdaf8 100644
--- a/libstdc++-v3/include/std/flat_map
+++ b/libstdc++-v3/include/std/flat_map
@@ -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();
diff --git a/libstdc++-v3/testsuite/23_containers/flat_map/1.cc 
b/libstdc++-v3/testsuite/23_containers/flat_map/1.cc
index 04c2101aab13..096b9eeac3e4 100644
--- a/libstdc++-v3/testsuite/23_containers/flat_map/1.cc
+++ b/libstdc++-v3/testsuite/23_containers/flat_map/1.cc
@@ -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;
 }

Reply via email to