[libcxx-commits] [libcxx] [libcxx] implement LWG4148: unique_ptr::operator* should not allow dangling references (PR #128213)

Mohamed Atef via libcxx-commits libcxx-commits at lists.llvm.org
Sat Nov 8 08:30:55 PST 2025


================
@@ -265,6 +265,14 @@ class _LIBCPP_UNIQUE_PTR_TRIVIAL_ABI unique_ptr {
 
   _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX23 __add_lvalue_reference_t<_Tp> operator*() const
       _NOEXCEPT_(_NOEXCEPT_(*std::declval<pointer>())) {
+    // TODO(LLVM-21): Remove this workaround
+#if __has_builtin(__reference_converts_from_temporary) ||                                                              \
+    (defined(_LIBCPP_CLANG_VER) &&                                                                                     \
+     ((!defined(__ANDROID__) && _LIBCPP_CLANG_VER >= 1901) || (defined(__ANDROID__) && _LIBCPP_CLANG_VER >= 2000)))
+    static_assert(
+        !__reference_converts_from_temporary(__add_lvalue_reference_t<_Tp>, decltype(*std::declval<pointer>())),
+        "Reference type _Tp must not convert from a temporary object");
+#endif
----------------
elhewaty wrote:

BTW, I am trying to run the test file in my local, and I get the following error,

```
CXX=../build/bin/clang++ ../build/bin/llvm-lit -sv libcxx/test/libcxx/memory/

# .---command stderr------------
# | error: 'expected-error' diagnostics expected but not seen: 
# |   File * Line * (directive at /home/mohamed/Desktop/open-source/llvm/llvm-project/libcxx/test/libcxx/memory/unique_ptr.verify.cpp:23): static assertion failed{{.*}}'!__reference_converts_from_temporary(const int &, long &)': Reference type _Tp must not convert from a temporary object
# | 1 error generated.
# `-----------------------------
# error: command failed with exit status: 1
```
here is the test for reference:

```
#include <memory>

struct deleter {
  using pointer = long*;
  void operator()(pointer) const {}
};

void test() {
  long l = 0;
  std::unique_ptr<const int, deleter> p(&l);
  // expected-error-re@*:* {{static assertion failed{{.*}}'!__reference_converts_from_temporary(const int &, long &)': Reference type _Tp must not convert from a temporary object}}
  // expected-error@*:*{{returning reference to local temporary object}}
  std::ignore = *p; // expected-note {{requested here}}
}
```

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


More information about the libcxx-commits mailing list