diff options
author | Devtools Arcadia <arcadia-devtools@yandex-team.ru> | 2022-02-07 18:08:42 +0300 |
---|---|---|
committer | Devtools Arcadia <arcadia-devtools@mous.vla.yp-c.yandex.net> | 2022-02-07 18:08:42 +0300 |
commit | 1110808a9d39d4b808aef724c861a2e1a38d2a69 (patch) | |
tree | e26c9fed0de5d9873cce7e00bc214573dc2195b7 /library/cpp/messagebus/misc/weak_ptr.h | |
download | ydb-1110808a9d39d4b808aef724c861a2e1a38d2a69.tar.gz |
intermediate changes
ref:cde9a383711a11544ce7e107a78147fb96cc4029
Diffstat (limited to 'library/cpp/messagebus/misc/weak_ptr.h')
-rw-r--r-- | library/cpp/messagebus/misc/weak_ptr.h | 99 |
1 files changed, 99 insertions, 0 deletions
diff --git a/library/cpp/messagebus/misc/weak_ptr.h b/library/cpp/messagebus/misc/weak_ptr.h new file mode 100644 index 0000000000..70fdeb0e2a --- /dev/null +++ b/library/cpp/messagebus/misc/weak_ptr.h @@ -0,0 +1,99 @@ +#pragma once + +#include <util/generic/ptr.h> +#include <util/system/mutex.h> + +template <typename T> +struct TWeakPtr; + +template <typename TSelf> +struct TWeakRefCounted { + template <typename> + friend struct TWeakPtr; + +private: + struct TRef: public TAtomicRefCount<TRef> { + TMutex Mutex; + TSelf* Outer; + + TRef(TSelf* outer) + : Outer(outer) + { + } + + void Release() { + TGuard<TMutex> g(Mutex); + Y_ASSERT(!!Outer); + Outer = nullptr; + } + + TIntrusivePtr<TSelf> Get() { + TGuard<TMutex> g(Mutex); + Y_ASSERT(!Outer || Outer->RefCount() > 0); + return Outer; + } + }; + + TAtomicCounter Counter; + TIntrusivePtr<TRef> RefPtr; + +public: + TWeakRefCounted() + : RefPtr(new TRef(static_cast<TSelf*>(this))) + { + } + + void Ref() { + Counter.Inc(); + } + + void UnRef() { + if (Counter.Dec() == 0) { + RefPtr->Release(); + + // drop is to prevent dtor from reading it + RefPtr.Drop(); + + delete static_cast<TSelf*>(this); + } + } + + void DecRef() { + Counter.Dec(); + } + + unsigned RefCount() const { + return Counter.Val(); + } +}; + +template <typename T> +struct TWeakPtr { +private: + typedef TIntrusivePtr<typename T::TRef> TRefPtr; + TRefPtr RefPtr; + +public: + TWeakPtr() { + } + + TWeakPtr(T* t) { + if (!!t) { + RefPtr = t->RefPtr; + } + } + + TWeakPtr(TIntrusivePtr<T> t) { + if (!!t) { + RefPtr = t->RefPtr; + } + } + + TIntrusivePtr<T> Get() { + if (!RefPtr) { + return nullptr; + } else { + return RefPtr->Get(); + } + } +}; |