[libc++] Add another const_cast to support hash_map copy assignment

There was one more const_cast needed after #183223 without which
copy assignment of hash_map was broken. Add it, together with a copy
assignment test.

Reviewers: ldionne

Pull Request: https://github.com/llvm/llvm-project/pull/188660
This commit is contained in:
Peter Collingbourne
2026-03-26 12:12:01 -07:00
committed by GitHub
parent f8fe67c998
commit 5b8c175804
2 changed files with 17 additions and 5 deletions

View File

@@ -19,6 +19,7 @@
#include <__cstddef/ptrdiff_t.h>
#include <__cstddef/size_t.h>
#include <__functional/hash.h>
#include <__fwd/pair.h>
#include <__iterator/iterator_traits.h>
#include <__math/rounding_functions.h>
#include <__memory/addressof.h>
@@ -1042,15 +1043,22 @@ private:
_LIBCPP_HIDE_FROM_ABI __next_pointer __detach() _NOEXCEPT;
template <class _From, class _ValueT = _Tp, __enable_if_t<__is_hash_value_type<_ValueT>::value, int> = 0>
template <class _From,
class _ValueT = _Tp,
__enable_if_t<__is_hash_value_type<_ValueT>::value || __is_pair_v<_ValueT>, int> = 0>
_LIBCPP_HIDE_FROM_ABI void __assign_value(__get_hash_node_value_type_t<_Tp>& __lhs, _From&& __rhs) {
// This is technically UB, since the object was constructed as `const`.
// Clang doesn't optimize on this currently though.
const_cast<key_type&>(__lhs.first) = const_cast<__copy_cvref_t<_From, key_type>&&>(__rhs.first);
__lhs.second = std::forward<_From>(__rhs).second;
//
// The enable_if check for __is_pair_v is only needed to support
// __gnu_cxx::hash_map and may be removed if hash_map is removed.
const_cast<__remove_const_t<decltype(__lhs.first)>&>(__lhs.first) = std::forward<_From>(__rhs).first;
__lhs.second = std::forward<_From>(__rhs).second;
}
template <class _From, class _ValueT = _Tp, __enable_if_t<!__is_hash_value_type<_ValueT>::value, int> = 0>
template <class _From,
class _ValueT = _Tp,
__enable_if_t<!__is_hash_value_type<_ValueT>::value && !__is_pair_v<_ValueT>, int> = 0>
_LIBCPP_HIDE_FROM_ABI void __assign_value(_Tp& __lhs, _From&& __rhs) {
__lhs = std::forward<_From>(__rhs);
}

View File

@@ -6,7 +6,7 @@
//
//===----------------------------------------------------------------------===//
// ADDITIONAL_COMPILE_FLAGS: -Wno-deprecated
// ADDITIONAL_COMPILE_FLAGS: -Wno-deprecated -Wno-deprecated-copy
// hash_map::hash_map(const hash_map&)
@@ -23,5 +23,9 @@ int main(int, char**) {
assert(map2.size() == 2);
map.insert(std::make_pair(3, 1));
map2 = map;
assert(map2.size() == 3);
return 0;
}