Skip to content

Commit 340bbb1

Browse files
committed
add shared_ref::operator weak_ptr()
1 parent 7016c64 commit 340bbb1

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

src/utki/shared_ref.hpp

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,14 @@ class shared_ref
126126
return this->p;
127127
}
128128

129+
/**
130+
* @brief Automatic conversion to weak_ptr.
131+
*/
132+
operator std::weak_ptr<object_type>() const noexcept
133+
{
134+
return this->p;
135+
}
136+
129137
/**
130138
* @brief Automatic conversion to shared_ptr pointing to const object.
131139
*/
@@ -135,6 +143,15 @@ class shared_ref
135143
return this->p;
136144
}
137145

146+
/**
147+
* @brief Automatic conversion to weak_ptr pointing to const object.
148+
*/
149+
template <typename enable_type = object_type>
150+
operator std::weak_ptr<std::enable_if_t<!std::is_const_v<enable_type>, const enable_type>>() const noexcept
151+
{
152+
return this->p;
153+
}
154+
138155
/**
139156
* @brief Get reference to the object.
140157
*

tests/unit/src/shared_ref.cpp

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -215,7 +215,7 @@ const tst::set set("shared_ref", [](tst::suite& suite) {
215215
tst::check_eq(vec[2].get().a_0, 1, SL);
216216
});
217217

218-
suite.add("operator_shared_ptr", []() {
218+
suite.add("operator_convert_to_shared_ptr", []() {
219219
auto a = utki::make_shared<a1>(13);
220220

221221
utki::shared_ref<const a1> ca = a;
@@ -242,6 +242,37 @@ const tst::set set("shared_ref", [](tst::suite& suite) {
242242
tst::check(cp2, SL);
243243
tst::check_eq(cp2, ca.to_shared_ptr(), SL);
244244
});
245+
246+
suite.add("operator_convert_to_weak_ptr", []() {
247+
auto a = utki::make_shared<a1>(13);
248+
249+
utki::shared_ref<const a1> ca = a;
250+
251+
std::weak_ptr<a1> p;
252+
std::weak_ptr<const a1> cp1;
253+
std::weak_ptr<const a1> cp2;
254+
255+
tst::check(a.to_shared_ptr(), SL);
256+
tst::check(ca.to_shared_ptr(), SL);
257+
tst::check(p.expired(), SL);
258+
tst::check(cp1.expired(), SL);
259+
260+
p = a;
261+
cp1 = a;
262+
cp2 = ca;
263+
264+
tst::check(!p.expired(), SL);
265+
tst::check(p.lock(), SL);
266+
tst::check_eq(p.lock(), a.to_shared_ptr(), SL);
267+
268+
tst::check(!cp1.expired(), SL);
269+
tst::check(cp1.lock(), SL);
270+
tst::check_eq(cp1.lock(), ca.to_shared_ptr(), SL);
271+
272+
tst::check(!cp2.expired(), SL);
273+
tst::check(cp2.lock(), SL);
274+
tst::check_eq(cp2.lock(), ca.to_shared_ptr(), SL);
275+
});
245276
});
246277

247278
} // namespace

0 commit comments

Comments
 (0)