[libcxx-commits] [libcxx] [libc++] Fix missing 'get_new_handler()' for Windows builds (PR #150182)

via libcxx-commits libcxx-commits at lists.llvm.org
Mon Jan 5 10:42:11 PST 2026


================
@@ -26,11 +24,33 @@
 
 #if defined(_LIBPCPP_DEFINE_NEW_HANDLER)
 
-namespace std { // purposefully not versioned
-
 static constinit std::new_handler __new_handler = nullptr;
 
-new_handler set_new_handler(new_handler handler) noexcept { return __libcpp_atomic_exchange(&__new_handler, handler); }
+#  ifdef _LIBCPP_ABI_VCRUNTIME
+// to avoid including <new.h>
+using _new_h = int(__cdecl*)(size_t);
+extern "C" _new_h __cdecl _set_new_handler(_new_h);
+
+namespace {
+// adapter for _callnewh
+int __cdecl _new_handler_adapter(size_t) {
+  std::__libcpp_atomic_load (&__new_handler)();
+  return 1;
+}
+} // namespace
+#  endif
+
+namespace std { // purposefully not versioned
+
+new_handler set_new_handler(new_handler handler) noexcept {
+#  ifdef _LIBCPP_ABI_VCRUNTIME
+  auto old = __libcpp_atomic_exchange(&__new_handler, handler);
+  _set_new_handler(handler ? _new_handler_adapter : nullptr);
+  return old;
+#  else
+  return __libcpp_atomic_exchange(&__new_handler, handler);
+#  endif
+}
----------------
siradam7th wrote:

UCRT does not expose a `get_new_handler` so we can't use it because it does not exist.
- MSVC STL implements both `set_new_handler` and `get_new_handler`.

The available functions are `_set_new_handler` and `_get_new_handler` which do not have a conforming signature so they cannot be used directly, they are defined in `<new.h>`.

This patch uses `_set_new_handler` to implement the functionality just like MSVC STL does, and similarly does not use `_get_new_handler` because of the non-conforming signature since we cannot return its result without having to wrap the handler inside yet another function, plus there is no need to use that function since we are storing the handler before setting it anyway, we can just return it directly.
This patch makes it so that we have the same behaviour as the MSVC STL.

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


More information about the libcxx-commits mailing list