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:
parent
dd716dc9be
commit
234f029940
1 changed files with 25 additions and 7 deletions
|
|
@ -17,6 +17,12 @@ private:
|
||||||
|
|
||||||
std::shared_ptr<T> p;
|
std::shared_ptr<T> p;
|
||||||
|
|
||||||
|
void assertNonNull()
|
||||||
|
{
|
||||||
|
if (!p)
|
||||||
|
throw std::invalid_argument("null pointer cast to ref");
|
||||||
|
}
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
|
||||||
using element_type = T;
|
using element_type = T;
|
||||||
|
|
@ -24,15 +30,19 @@ public:
|
||||||
explicit ref(const std::shared_ptr<T> & p)
|
explicit ref(const std::shared_ptr<T> & p)
|
||||||
: p(p)
|
: p(p)
|
||||||
{
|
{
|
||||||
if (!p)
|
assertNonNull();
|
||||||
throw std::invalid_argument("null pointer cast to ref");
|
}
|
||||||
|
|
||||||
|
explicit ref(std::shared_ptr<T> && p)
|
||||||
|
: p(std::move(p))
|
||||||
|
{
|
||||||
|
assertNonNull();
|
||||||
}
|
}
|
||||||
|
|
||||||
explicit ref(T * p)
|
explicit ref(T * p)
|
||||||
: p(p)
|
: p(p)
|
||||||
{
|
{
|
||||||
if (!p)
|
assertNonNull();
|
||||||
throw std::invalid_argument("null pointer cast to ref");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
T * operator->() const
|
T * operator->() const
|
||||||
|
|
@ -45,14 +55,22 @@ public:
|
||||||
return *p;
|
return *p;
|
||||||
}
|
}
|
||||||
|
|
||||||
operator std::shared_ptr<T>() const
|
std::shared_ptr<T> get_ptr() const &
|
||||||
{
|
{
|
||||||
return p;
|
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>
|
template<typename T2>
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue