[libcxx-commits] [libcxx] [libc++] Avoid type-punning between __Value_type and pair (PR #134819)

A. Jiang via libcxx-commits libcxx-commits at lists.llvm.org
Wed Apr 9 19:12:27 PDT 2025


================
@@ -1276,6 +1267,32 @@ private:
   }
   _LIBCPP_HIDE_FROM_ABI void __move_assign_alloc(__tree&, false_type) _NOEXCEPT {}
 
+  template <class _From, __enable_if_t<__is_pair_v<__remove_cvref_t<_From> >, int> = 0>
+  _LIBCPP_HIDE_FROM_ABI static void __assign_value(__get_node_value_type_t<value_type>& __lhs, _From&& __rhs) {
+    using __punned_type = pair<typename _NodeTypes::key_type, typename _NodeTypes::mapped_type>;
+
+    reinterpret_cast<__punned_type&>(__lhs) = reinterpret_cast<__copy_cvref_t<_From, __punned_type>&&>(__rhs);
----------------
frederick-vs-ja wrote:

Hmm, it seems that core language UB can't be avoided in the current strategy (for which I submitted [CWG2514](https://cplusplus.github.io/CWG/issues/2514.html)). We need to do different operations in constant evaluation. (No change for this is requested for this PR.)

Now this PR assumes that `pair<K, V>` and `pair<const K, V>` have the same layout, which is not guaranteed - especially when there's a user-defined `pair` specialization. Is it possible to use less scary `const_cast`?

https://github.com/llvm/llvm-project/pull/134819


More information about the libcxx-commits mailing list