Skip to content

Commit 234f029

Browse files
committed
Add consuming ref <-> std::share_ptr methods/ctrs
This can help churning ref counts when we don't need to.
1 parent dd716dc commit 234f029

File tree

1 file changed

+25
-7
lines changed
  • src/libutil/include/nix/util

1 file changed

+25
-7
lines changed

src/libutil/include/nix/util/ref.hh

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,22 +17,32 @@ private:
1717

1818
std::shared_ptr<T> p;
1919

20+
void assertNonNull()
21+
{
22+
if (!p)
23+
throw std::invalid_argument("null pointer cast to ref");
24+
}
25+
2026
public:
2127

2228
using element_type = T;
2329

2430
explicit ref(const std::shared_ptr<T> & p)
2531
: p(p)
2632
{
27-
if (!p)
28-
throw std::invalid_argument("null pointer cast to ref");
33+
assertNonNull();
34+
}
35+
36+
explicit ref(std::shared_ptr<T> && p)
37+
: p(std::move(p))
38+
{
39+
assertNonNull();
2940
}
3041

3142
explicit ref(T * p)
3243
: p(p)
3344
{
34-
if (!p)
35-
throw std::invalid_argument("null pointer cast to ref");
45+
assertNonNull();
3646
}
3747

3848
T * operator->() const
@@ -45,14 +55,22 @@ public:
4555
return *p;
4656
}
4757

48-
operator std::shared_ptr<T>() const
58+
std::shared_ptr<T> get_ptr() const &
4959
{
5060
return p;
5161
}
5262

53-
std::shared_ptr<T> get_ptr() const
63+
std::shared_ptr<T> get_ptr() &&
5464
{
55-
return p;
65+
return std::move(p);
66+
}
67+
68+
/**
69+
* Convenience to avoid explicit `get_ptr()` call in some cases.
70+
*/
71+
operator std::shared_ptr<T>(this auto && self)
72+
{
73+
return std::forward<decltype(self)>(self).get_ptr();
5674
}
5775

5876
template<typename T2>

0 commit comments

Comments
 (0)