Skip to content

Commit 8f7bec9

Browse files
committed
[libcxx] implement LWG4148: unique_ptr::operator* should not allow dangling references
1 parent 73ad78c commit 8f7bec9

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

libcxx/include/__memory/unique_ptr.h

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -261,7 +261,10 @@ class _LIBCPP_UNIQUE_PTR_TRIVIAL_ABI _LIBCPP_TEMPLATE_VIS unique_ptr {
261261
}
262262

263263
_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX23 __add_lvalue_reference_t<_Tp> operator*() const
264-
_NOEXCEPT_(_NOEXCEPT_(*std::declval<pointer>())) {
264+
_NOEXCEPT_(_NOEXCEPT_(*std::declval<pointer>()))
265+
// TODO: use reference_converts_from_temporary_v once implemented.
266+
requires(!__reference_converts_from_temporary(__add_lvalue_reference_t<_Tp>, decltype(*declval<pointer>())))
267+
{
265268
return *__ptr_;
266269
}
267270
_LIBCPP_HIDE_FROM_ABI _LIBCPP_CONSTEXPR_SINCE_CXX23 pointer operator->() const _NOEXCEPT { return __ptr_; }
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
//===----------------------------------------------------------------------===//
2+
//
3+
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4+
// See https://llvm.org/LICENSE.txt for license information.
5+
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6+
//
7+
//===----------------------------------------------------------------------===//
8+
9+
// <memory>
10+
11+
#include <iostream>
12+
#include <memory>
13+
14+
using namespace std;
15+
16+
struct deleter {
17+
using pointer = long*;
18+
void operator()(pointer) const {}
19+
};
20+
21+
int main(int argc, char const *argv[]) {
22+
long l = 0;
23+
std::unique_ptr<const int, deleter> p(&l);
24+
// Error: indirection requires pointer operand ('std::unique_ptr<const int, deleter>' invalid)
25+
int i = *p;
26+
cout << i << endl;
27+
return 0;
28+
}

0 commit comments

Comments
 (0)