-
Notifications
You must be signed in to change notification settings - Fork 29
/
CRefCountable.h
80 lines (66 loc) · 1.34 KB
/
CRefCountable.h
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
#pragma once
#include <cstdint>
#include <atomic>
#include <mutex>
#include <unordered_set>
namespace alt
{
template<class T> class WeakRefStore;
class IWeakRef
{
public:
virtual void OnDestroy() = 0;
};
class CRefCountable
{
public:
virtual uint64_t GetRefCount() const { return refCount; }
virtual void AddRef() const { ++refCount; }
virtual bool AddRefIfExists() const
{
for (;;)
{
uint_fast64_t cur = refCount;
if (cur == 0)
{
return false;
}
if (refCount.compare_exchange_strong(cur, cur + 1))
{
break;
}
}
return true;
}
virtual void RemoveRef() const
{
if (--refCount == 0)
{
{
std::unique_lock lock{ weakRefsMutex };
for (auto ref : weakRefs)
ref->OnDestroy();
}
delete this;
}
}
virtual const std::type_info& GetTypeInfo() const = 0;
protected:
virtual ~CRefCountable() = default;
virtual void AddWeakRef(IWeakRef* ref) const
{
std::unique_lock lock{ weakRefsMutex };
weakRefs.insert(ref);
}
virtual void RemoveWeakRef(IWeakRef* ref) const
{
std::unique_lock lock{ weakRefsMutex };
weakRefs.erase(ref);
}
private:
mutable std::atomic_uint64_t refCount{ 0 };
mutable std::mutex weakRefsMutex;
mutable std::unordered_set<IWeakRef*> weakRefs;
template<class T> friend class WeakRefStore;
};
}