| 10 | |
| 11 | template <class T> |
| 12 | class TWeakPtr |
| 13 | { |
| 14 | public: |
| 15 | using TUnderlying = T; |
| 16 | using element_type = T; |
| 17 | |
| 18 | //! Empty constructor. |
| 19 | TWeakPtr() = default; |
| 20 | |
| 21 | TWeakPtr(std::nullptr_t) |
| 22 | { } |
| 23 | |
| 24 | //! Constructor from an unqualified reference. |
| 25 | /*! |
| 26 | * Note that this constructor could be racy due to unsynchronized operations |
| 27 | * on the object and on the counter. |
| 28 | */ |
| 29 | explicit TWeakPtr(T* p) noexcept |
| 30 | : T_(p) |
| 31 | { |
| 32 | |
| 33 | #if defined(_tsan_enabled_) |
| 34 | if (T_) { |
| 35 | RefCounter_ = GetRefCounter(T_); |
| 36 | } |
| 37 | #endif |
| 38 | AcquireRef(); |
| 39 | } |
| 40 | |
| 41 | //! Constructor from a strong reference. |
| 42 | TWeakPtr(const TIntrusivePtr<T>& ptr) noexcept |
| 43 | : TWeakPtr(ptr.Get()) |
| 44 | { } |
| 45 | |
| 46 | //! Constructor from a strong reference with an upcast. |
| 47 | template <class U, class = typename std::enable_if_t<std::is_convertible_v<U*, T*>>> |
| 48 | TWeakPtr(const TIntrusivePtr<U>& ptr) noexcept |
| 49 | : TWeakPtr(ptr.Get()) |
| 50 | { |
| 51 | static_assert( |
| 52 | std::derived_from<T, TRefCountedBase>, |
| 53 | "Cast allowed only for types derived from TRefCountedBase"); |
| 54 | } |
| 55 | |
| 56 | //! Copy constructor. |
| 57 | TWeakPtr(const TWeakPtr& other) noexcept |
| 58 | : T_(other.T_) |
| 59 | #if defined(_tsan_enabled_) |
| 60 | , RefCounter_(other.RefCounter_) |
| 61 | #endif |
| 62 | { |
| 63 | AcquireRef(); |
| 64 | } |
| 65 | |
| 66 | //! Copy constructor with an upcast. |
| 67 | template <class U, class = typename std::enable_if_t<std::is_convertible_v<U*, T*>>> |
| 68 | TWeakPtr(const TWeakPtr<U>& other) noexcept |
| 69 | : TWeakPtr(other.Lock()) |