-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathCRefCountable.h
More file actions
57 lines (47 loc) · 971 Bytes
/
CRefCountable.h
File metadata and controls
57 lines (47 loc) · 971 Bytes
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
#pragma once
#include <cstdint>
#include <atomic>
#include <mutex>
#include <unordered_set>
namespace alt
{
class IWeakRef
{
public:
virtual void OnDestroy() = 0;
};
class CRefCountable
{
public:
virtual uint64_t GetRefCount() const { return refCount; }
virtual void AddRef() const { ++refCount; }
virtual void RemoveRef() const
{
if (--refCount == 0)
{
{
std::unique_lock lock{ weakRefsMutex };
for (auto ref : weakRefs)
ref->OnDestroy();
}
delete this;
}
}
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);
}
protected:
virtual ~CRefCountable() = default;
private:
mutable std::atomic_uint64_t refCount{ 0 };
mutable std::mutex weakRefsMutex;
mutable std::unordered_set<IWeakRef*> weakRefs;
};
}