aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/yt/memory/weak_ptr.h
blob: 7a789f3b0bd5d39e80dcdebe8cf6ba276664cd6f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
#pragma once

#include "ref_counted.h" 

#include <util/generic/hash.h>

namespace NYT {

////////////////////////////////////////////////////////////////////////////////

template <class T> 
class TWeakPtr
{
public:
    typedef T TUnderlying;

    //! Empty constructor.
    TWeakPtr() = default;

    TWeakPtr(std::nullptr_t)
    { }

    //! Constructor from an unqualified reference.
    /*!
     * Note that this constructor could be racy due to unsynchronized operations
     * on the object and on the counter.
     */
    explicit TWeakPtr(T* p) noexcept
        : T_(p)
    {
 
#if defined(_tsan_enabled_) 
        if (T_) {
            RefCounter_ = GetRefCounter(T_); 
        }
#endif 
        AcquireRef(); 
    }

    //! Constructor from a strong reference.
    TWeakPtr(const TIntrusivePtr<T>& ptr) noexcept 
        : TWeakPtr(ptr.Get()) 
    { } 

    //! Constructor from a strong reference with an upcast. 
    template <class U, class = typename std::enable_if_t<std::is_convertible_v<U*, T*>>>
    TWeakPtr(const TIntrusivePtr<U>& ptr) noexcept 
        : TWeakPtr(ptr.Get()) 
    { 
        static_assert( 
            std::is_base_of_v<TRefCountedBase, T>, 
            "Cast allowed only for types derived from TRefCountedBase"); 
    } 
 
    //! Copy constructor.
    TWeakPtr(const TWeakPtr& other) noexcept 
        : TWeakPtr(other.T_) 
    { } 

    //! Copy constructor with an upcast.
    template <class U, class = typename std::enable_if_t<std::is_convertible_v<U*, T*>>>
    TWeakPtr(const TWeakPtr<U>& other) noexcept 
        : TWeakPtr(other.Lock()) 
    {
        static_assert( 
            std::is_base_of_v<TRefCountedBase, T>, 
            "Cast allowed only for types derived from TRefCountedBase"); 
    }

    //! Move constructor.
    TWeakPtr(TWeakPtr&& other) noexcept 
    {
        other.Swap(*this); 
    }

    //! Move constructor with an upcast.
    template <class U, class = typename std::enable_if_t<std::is_convertible_v<U*, T*>>>
    TWeakPtr(TWeakPtr<U>&& other) noexcept 
    {
        static_assert( 
            std::is_base_of_v<TRefCountedBase, T>, 
            "Cast allowed only for types derived from TRefCountedBase"); 
        TIntrusivePtr<U> strongOther = other.Lock();
        if (strongOther) {
            T_ = other.T_;
            other.T_ = nullptr; 

#if defined(_tsan_enabled_) 
            RefCounter_ = other.RefCounter_; 
            other.RefCounter_ = nullptr; 
#endif 
        }
    }

    //! Destructor.
    ~TWeakPtr()
    {
        ReleaseRef(); 
    }

    //! Assignment operator from a strong reference.
    template <class U>
    TWeakPtr& operator=(const TIntrusivePtr<U>& ptr) noexcept 
    {
        static_assert(
            std::is_convertible_v<U*, T*>,
            "U* must be convertible to T*"); 
        TWeakPtr(ptr).Swap(*this); 
        return *this;
    }

    //! Copy assignment operator.
    TWeakPtr& operator=(const TWeakPtr& other) noexcept
    {
        TWeakPtr(other).Swap(*this);
        return *this;
    }

    //! Copy assignment operator with an upcast.
    template <class U>
    TWeakPtr& operator=(const TWeakPtr<U>& other) noexcept
    {
        static_assert(
            std::is_convertible_v<U*, T*>,
            "U* must be convertible to T*"); 
        TWeakPtr(other).Swap(*this);
        return *this;
    }

    //! Move assignment operator.
    TWeakPtr& operator=(TWeakPtr&& other) noexcept
    {
        other.Swap(*this); 
        return *this;
    }

    //! Move assignment operator with an upcast.
    template <class U>
    TWeakPtr& operator=(TWeakPtr<U>&& other) noexcept
    {
        static_assert( 
            std::is_convertible_v<U*, T*>,
            "U* must be convertible to T*"); 
        TWeakPtr(std::move(other)).Swap(*this);
        return *this;
    }

    //! Drop the pointer.
    void Reset() // noexcept
    {
        TWeakPtr().Swap(*this);
    }

    //! Replace the pointer with a specified one.
    void Reset(T* p) // noexcept
    {
        TWeakPtr(p).Swap(*this);
    }

    //! Replace the pointer with a specified one.
    template <class U>
    void Reset(const TIntrusivePtr<U>& ptr) // noexcept 
    {
        static_assert(
            std::is_convertible_v<U*, T*>,
            "U* must be convertible to T*"); 
        TWeakPtr(ptr).Swap(*this); 
    }

    //! Swap the pointer with the other one. 
    void Swap(TWeakPtr& other) noexcept 
    { 
        DoSwap(T_, other.T_); 
#if defined(_tsan_enabled_) 
        DoSwap(RefCounter_, other.RefCounter_); 
#endif 
    } 
 
    //! Acquire a strong reference to the pointee and return a strong pointer.
    TIntrusivePtr<T> Lock() const noexcept
    {
        return T_ && RefCounter()->TryRef() 
            ? TIntrusivePtr<T>(T_, false)
            : TIntrusivePtr<T>();
    }

    bool IsExpired() const noexcept 
    {
        return !T_ || (RefCounter()->GetRefCount() == 0); 
    }

private: 
    void AcquireRef() 
    {
        if (T_) { 
            RefCounter()->WeakRef(); 
        } 
    }

    void ReleaseRef() 
    { 
        if (T_) { 
            // Support incomplete type. 
            if (RefCounter()->WeakUnref()) { 
                DeallocateRefCounted(T_); 
            } 
        } 
    } 
 
    template <class U>
    friend class TWeakPtr;
    template <class U>
    friend struct ::THash;

    T* T_ = nullptr;
#if defined(_tsan_enabled_) 
    const TRefCounter* RefCounter_ = nullptr; 
 
    const TRefCounter* RefCounter() const 
    { 
        return RefCounter_; 
    } 
#else 
    const TRefCounter* RefCounter() const 
    { 
        return GetRefCounter(T_); 
    } 
#endif 
};

////////////////////////////////////////////////////////////////////////////////

//! Creates a weak pointer wrapper for a given raw pointer.
//! Compared to |TWeakPtr<T>::ctor|, type inference enables omitting |T|.
template <class T>
TWeakPtr<T> MakeWeak(T* p)
{
    return TWeakPtr<T>(p);
}

//! Creates a weak pointer wrapper for a given intrusive pointer.
//! Compared to |TWeakPtr<T>::ctor|, type inference enables omitting |T|.
template <class T>
TWeakPtr<T> MakeWeak(const TIntrusivePtr<T>& p)
{
    return TWeakPtr<T>(p);
}

//! A helper for acquiring weak pointer for pointee, resetting intrusive pointer and then
//! returning the pointee reference count using the acquired weak pointer.
//! This helper is designed for best effort in checking that the object is not leaked after
//! destructing (what seems to be) the last pointer to it.
//! NB: it is possible to rewrite this helper making it working event with intrinsic refcounted objects,
//! but it requires much nastier integration with the intrusive pointer destruction routines.
template <typename T>
int ResetAndGetResidualRefCount(TIntrusivePtr<T>& pointer)
{
    auto weakPointer = MakeWeak(pointer);
    pointer.Reset();
    if (pointer = weakPointer.Lock()) {
        // This _may_ return 0 if we are again the only holder of the pointee.
        return pointer->GetRefCount() - 1;
    } else {
        return 0;
    }
}

////////////////////////////////////////////////////////////////////////////////

// TODO(sandello): Kill comparsions.
template <class T>
bool operator<(const TWeakPtr<T>& lhs, const TWeakPtr<T>& rhs)
{
    return lhs.Lock().Get() < rhs.Lock().Get();
}

template <class T>
bool operator>(const TWeakPtr<T>& lhs, const TWeakPtr<T>& rhs)
{
    return lhs.Lock().Get() > rhs.Lock().Get();
}

template <class T, class U>
bool operator==(const TWeakPtr<T>& lhs, const TWeakPtr<U>& rhs)
{
    static_assert(
        std::is_convertible_v<U*, T*>,
        "U* must be convertible to T*"); 
    return lhs.Lock().Get() == rhs.Lock().Get();
}

template <class T, class U>
bool operator!=(const TWeakPtr<T>& lhs, const TWeakPtr<U>& rhs)
{
    static_assert(
        std::is_convertible_v<U*, T*>,
        "U* must be convertible to T*"); 
    return lhs.Lock().Get() != rhs.Lock().Get();
}

////////////////////////////////////////////////////////////////////////////////

} // namespace NYT


//! A hasher for TWeakPtr.
template <class T>
struct THash<NYT::TWeakPtr<T>>
{
    size_t operator () (const NYT::TWeakPtr<T>& ptr) const
    {
        return THash<const NYT::TRefCountedBase*>()(ptr.T_); 
    }
};