[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:01 PST 2025


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

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


>From 8f7bec983b551545885752bf960d49dcbe05b0dc Mon Sep 17 00:00:00 2001
From: Mohamed Atef <mohamedatef1698 at gmail.com>
Date: Fri, 21 Feb 2025 20:13:33 +0200
Subject: [PATCH] [libcxx] implement LWG4148: unique_ptr::operator* should not
 allow dangling references

---
 libcxx/include/__memory/unique_ptr.h          |  5 +++-
 .../libcxx/memory/unique_ptr.compile.fail.cpp | 28 +++++++++++++++++++
 2 files changed, 32 insertions(+), 1 deletion(-)
 create mode 100644 libcxx/test/libcxx/memory/unique_ptr.compile.fail.cpp

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



More information about the libcxx-commits mailing list