aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorPatrick Palka <ppalka@redhat.com>2025-06-06 09:34:17 -0400
committerPatrick Palka <ppalka@redhat.com>2025-06-06 09:35:11 -0400
commite75e42f315e1e8bb4befee8ed242bd241c182091 (patch)
treef49bdd8de85ec639f6d0ab34b71f0463e0798cf3
parentb2338ebf3e698589c69a521b4b4a7908dd959751 (diff)
downloadgcc-e75e42f315e1e8bb4befee8ed242bd241c182091.zip
gcc-e75e42f315e1e8bb4befee8ed242bd241c182091.tar.gz
gcc-e75e42f315e1e8bb4befee8ed242bd241c182091.tar.bz2
libstdc++: Fix flat_map::operator[] for const lvalue keys [PR120432]
The const lvalue operator[] overload wasn't properly forwarding the key type to the generic overload, causing a hard error for const keys. Rather than correcting the forwarded type this patch just makes the non-template overloads call try_emplace directly instead. That way we can remove the non-standard same_as constraint on the generic overload and match the spec more closely. PR libstdc++/120432 libstdc++-v3/ChangeLog: * include/std/flat_map (flat_map::operator[]): Make the non-template overloads call try_emplace directly. Remove non-standard same_as constraint on the template overload. * testsuite/23_containers/flat_map/1.cc (test08): New test. Reviewed-by: Tomasz KamiƄski <tkaminsk@redhat.com> Reviewed-by: Jonathan Wakely <jwakely@redhat.com> (cherry picked from commit 91ed3248ce26aaaee4d7471aa4edbc07b3f1a90e)
-rw-r--r--libstdc++-v3/include/std/flat_map6
-rw-r--r--libstdc++-v3/testsuite/23_containers/flat_map/1.cc10
2 files changed, 13 insertions, 3 deletions
diff --git a/libstdc++-v3/include/std/flat_map b/libstdc++-v3/include/std/flat_map
index 4bd4963..de006ad 100644
--- a/libstdc++-v3/include/std/flat_map
+++ b/libstdc++-v3/include/std/flat_map
@@ -1148,14 +1148,14 @@ _GLIBCXX_BEGIN_NAMESPACE_VERSION
// element access
mapped_type&
operator[](const key_type& __x)
- { return operator[]<const key_type>(__x); }
+ { return try_emplace(__x).first->second; }
mapped_type&
operator[](key_type&& __x)
- { return operator[]<key_type>(std::move(__x)); }
+ { return try_emplace(std::move(__x)).first->second; }
template<typename _Key2>
- requires same_as<remove_cvref_t<_Key2>, _Key> || __transparent_comparator<_Compare>
+ requires __transparent_comparator<_Compare>
mapped_type&
operator[](_Key2&& __x)
{ return try_emplace(std::forward<_Key2>(__x)).first->second; }
diff --git a/libstdc++-v3/testsuite/23_containers/flat_map/1.cc b/libstdc++-v3/testsuite/23_containers/flat_map/1.cc
index 9d99796..d7f27a0 100644
--- a/libstdc++-v3/testsuite/23_containers/flat_map/1.cc
+++ b/libstdc++-v3/testsuite/23_containers/flat_map/1.cc
@@ -252,6 +252,15 @@ test07()
VERIFY( std::ranges::equal(m, (std::pair<int,int>[]){{3,4}}) );
}
+void
+test08()
+{
+ // PR libstdc++/120432 - flat_map operator[] is broken for const lvalue keys
+ std::flat_map<int, int> m;
+ const int k = 42;
+ m[k] = 0;
+}
+
int
main()
{
@@ -265,4 +274,5 @@ main()
test05();
test06();
test07();
+ test08();
}