1
1
Fork 0
mirror of https://github.com/NixOS/nix.git synced 2025-11-08 19:46:02 +01:00

Add consuming ref <-> std::share_ptr methods/ctrs

This can help churning ref counts when we don't need to.
This commit is contained in:
John Ericson 2025-10-27 15:39:58 -04:00
parent dd716dc9be
commit 234f029940

View file

@ -17,6 +17,12 @@ private:
std::shared_ptr<T> p;
void assertNonNull()
{
if (!p)
throw std::invalid_argument("null pointer cast to ref");
}
public:
using element_type = T;
@ -24,15 +30,19 @@ public:
explicit ref(const std::shared_ptr<T> & p)
: p(p)
{
if (!p)
throw std::invalid_argument("null pointer cast to ref");
assertNonNull();
}
explicit ref(std::shared_ptr<T> && p)
: p(std::move(p))
{
assertNonNull();
}
explicit ref(T * p)
: p(p)
{
if (!p)
throw std::invalid_argument("null pointer cast to ref");
assertNonNull();
}
T * operator->() const
@ -45,14 +55,22 @@ public:
return *p;
}
operator std::shared_ptr<T>() const
std::shared_ptr<T> get_ptr() const &
{
return p;
}
std::shared_ptr<T> get_ptr() const
std::shared_ptr<T> get_ptr() &&
{
return p;
return std::move(p);
}
/**
* Convenience to avoid explicit `get_ptr()` call in some cases.
*/
operator std::shared_ptr<T>(this auto && self)
{
return std::forward<decltype(self)>(self).get_ptr();
}
template<typename T2>