Skip to content

Commit b97a851

Browse files
committed
[ref_ptr]: nullptr_t support, return ref from _as_shared_ptr_unsafe
1 parent 2401d1d commit b97a851

2 files changed

Lines changed: 18 additions & 4 deletions

File tree

include/itlib/ref_ptr.hpp

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// itlib-ref_ptr v1.00
1+
// itlib-ref_ptr v1.01
22
//
33
// A ref-counting smart pointer with a stable use_count
44
//
@@ -28,7 +28,9 @@
2828
//
2929
// VERSION HISTORY
3030
//
31-
// 1.00 (2022-01-31) Initial release
31+
// 1.01 (2026-02-03) * nullptr_t constructor and assignment
32+
// * _as_shared_ptr_unsafe return ref to avoid copy
33+
// 1.00 (2026-01-31) Initial release
3234
//
3335
//
3436
// DOCUMENTATION
@@ -43,7 +45,7 @@
4345
// Since there is no weak_ptr, use_count() == 1 is reliable and can be used to
4446
// determine if the state is unique.
4547
//
46-
// An importaant use case for this is copy-on-write implementations.
48+
// An important use case for this is copy-on-write implementations.
4749
// ref_ptr<const T> would be a detached read-only view of a state.//
4850
// Since unique() is reliable, a safe "promotion" via a const_cast is possible
4951
// (We're not doing this until we have a good motivational use case)
@@ -83,6 +85,7 @@
8385
//
8486
#pragma once
8587
#include <memory>
88+
#include <cstddef>
8689
#include <type_traits>
8790

8891
namespace itlib {
@@ -104,6 +107,14 @@ class ref_ptr : private std::shared_ptr<T> {
104107
ref_ptr(ref_ptr&&) noexcept = default;
105108
ref_ptr& operator=(ref_ptr&&) noexcept = default;
106109

110+
ref_ptr(std::nullptr_t)
111+
: super(nullptr)
112+
{}
113+
ref_ptr& operator=(std::nullptr_t) {
114+
super::operator=(nullptr);
115+
return *this;
116+
}
117+
107118
template <typename U>
108119
ref_ptr(const ref_ptr<U>& ptr) noexcept
109120
: super(ptr)
@@ -156,7 +167,7 @@ class ref_ptr : private std::shared_ptr<T> {
156167
// only use as a last resort
157168
// when ref_ptr needs to be provided to an existing API relying on shared_ptr
158169
// be sure that the leaked shared_ptr will not be used to create weak_ptr-s
159-
std::shared_ptr<T> _as_shared_ptr_unsafe() const& noexcept {
170+
const std::shared_ptr<T>& _as_shared_ptr_unsafe() const& noexcept {
160171
return *this;
161172
}
162173
std::shared_ptr<T> _as_shared_ptr_unsafe() && noexcept {

test/t-ref_ptr-11.cpp

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,9 @@ TEST_CASE("ref_ptr") {
6363
CHECK_FALSE(p2);
6464
CHECK(p3.unique());
6565
CHECK(*p3 == 42);
66+
67+
p3 = nullptr;
68+
CHECK_FALSE(p3);
6669
}
6770

6871
// other casts

0 commit comments

Comments
 (0)