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

via libcxx-commits libcxx-commits at lists.llvm.org
Fri Feb 21 10:28:34 PST 2025


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-libcxx

Author: None (elhewaty)

<details>
<summary>Changes</summary>

Fixes: https://github.com/llvm/llvm-project/issues/118362


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


2 Files Affected:

- (modified) libcxx/include/__memory/unique_ptr.h (+4-1) 
- (added) libcxx/test/libcxx/memory/unique_ptr.compile.fail.cpp (+28) 


``````````diff
diff --git a/libcxx/include/__memory/unique_ptr.h b/libcxx/include/__memory/unique_ptr.h
index e8ef386f7f9fc..5e8335e971f6d 100644
--- a/libcxx/include/__memory/unique_ptr.h
+++ b/libcxx/include/__memory/unique_ptr.h
@@ -261,7 +261,10 @@ class _LIBCPP_UNIQUE_PTR_TRIVIAL_ABI _LIBCPP_TEMPLATE_VIS unique_ptr {
   }
 
   _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX23 __add_lvalue_reference_t<_Tp> operator*() const
-      _NOEXCEPT_(_NOEXCEPT_(*std::declval<pointer>())) {
+      _NOEXCEPT_(_NOEXCEPT_(*std::declval<pointer>()))
+    // TODO: use reference_converts_from_temporary_v once implemented.
+    requires(!__reference_converts_from_temporary(__add_lvalue_reference_t<_Tp>, decltype(*declval<pointer>())))
+  {
     return *__ptr_;
   }
   _LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX23 pointer operator->() const _NOEXCEPT { return __ptr_; }
diff --git a/libcxx/test/libcxx/memory/unique_ptr.compile.fail.cpp b/libcxx/test/libcxx/memory/unique_ptr.compile.fail.cpp
new file mode 100644
index 0000000000000..633247da3a5a4
--- /dev/null
+++ b/libcxx/test/libcxx/memory/unique_ptr.compile.fail.cpp
@@ -0,0 +1,28 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+// <memory>
+
+#include <iostream>
+#include <memory>
+
+using namespace std;
+
+struct deleter {
+  using pointer = long*;
+  void operator()(pointer) const {}
+};
+
+int main(int argc, char const *argv[]) {
+  long l = 0;
+  std::unique_ptr<const int, deleter> p(&l);
+  // Error: indirection requires pointer operand ('std::unique_ptr<const int, deleter>' invalid)
+  int i = *p;
+  cout << i << endl;
+  return 0;
+}
\ No newline at end of file

``````````

</details>


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


More information about the libcxx-commits mailing list