|
1
|
1 #pragma once
|
|
|
2
|
|
|
3 // PFC weakRef class
|
|
|
4 // Create weak references to objects that automatically become invalidated upon destruction of the object
|
|
|
5 // Note that this is NOT thread safe and meant for single thread usage. If you require thread safety, provide your own means, such as mutexlocking of weakRef::get() and the destruction of your objects.
|
|
|
6
|
|
|
7 #include <memory> // std::shared_ptr
|
|
|
8
|
|
|
9 namespace pfc {
|
|
|
10 typedef std::shared_ptr<const bool> weakRefKillSwitch_t;
|
|
|
11
|
|
|
12 template<typename target_t>
|
|
|
13 class weakRef {
|
|
|
14 typedef weakRef<target_t> self_t;
|
|
|
15 public:
|
|
|
16 static self_t _make(target_t * target, weakRefKillSwitch_t ks) {
|
|
|
17 self_t ret;
|
|
|
18 ret.m_target = target;
|
|
|
19 ret.m_ks = ks;
|
|
|
20 return ret;
|
|
|
21 }
|
|
|
22
|
|
|
23
|
|
|
24 bool isValid() const {
|
|
|
25 return m_ks && !*m_ks;
|
|
|
26 }
|
|
|
27
|
|
|
28 target_t * get() const {
|
|
|
29 if (!isValid()) return nullptr;
|
|
|
30 return m_target;
|
|
|
31 }
|
|
|
32 target_t * operator() () const {
|
|
|
33 return get();
|
|
|
34 }
|
|
|
35 private:
|
|
|
36 target_t * m_target = nullptr;
|
|
|
37 weakRefKillSwitch_t m_ks;
|
|
|
38 };
|
|
|
39
|
|
|
40 template<typename class_t>
|
|
|
41 class weakRefTarget {
|
|
|
42 public:
|
|
|
43 weakRefTarget() {}
|
|
|
44
|
|
|
45 typedef weakRef<class_t> weakRef_t;
|
|
|
46
|
|
|
47 weakRef<class_t> weakRef() {
|
|
|
48 PFC_ASSERT(!*m_ks);
|
|
|
49 class_t * ptr = static_cast<class_t*>(this);
|
|
|
50 return weakRef_t::_make(ptr, m_ks);
|
|
|
51 }
|
|
|
52
|
|
|
53 // Optional: explicitly invalidates all weak references to this object. Called implicitly by the destructor, but you can do it yourself earlier.
|
|
|
54 void weakRefShutdown() {
|
|
|
55 *m_ks = true;
|
|
|
56 }
|
|
|
57 ~weakRefTarget() {
|
|
|
58 weakRefShutdown();
|
|
|
59 }
|
|
|
60
|
|
|
61 // Optional: obtain a reference to the killswitch if you wish to use it directly
|
|
|
62 weakRefKillSwitch_t weakRefKS() const {
|
|
|
63 return m_ks;
|
|
|
64 }
|
|
|
65 private:
|
|
|
66 std::shared_ptr<bool> m_ks = std::make_shared<bool>(false);
|
|
|
67
|
|
|
68 weakRefTarget(const weakRefTarget &) = delete;
|
|
|
69 void operator=(const weakRefTarget &) = delete;
|
|
|
70 };
|
|
|
71 }
|