VCV Rack API v2
Loading...
Searching...
No Matches
weakptr.hpp
Go to the documentation of this file.
1#pragma once
2#include <common.hpp>
3
4
5namespace rack {
6
7
8struct WeakHandle {
9 void* ptr;
10 size_t count = 0;
11 WeakHandle(void* ptr) : ptr(ptr) {}
12};
13
14
16struct WeakBase {
18
20 if (weakHandle) {
21 weakHandle->ptr = nullptr;
22 }
23 }
24 size_t getWeakCount() {
25 if (!weakHandle)
26 return 0;
27 return weakHandle->count;
28 }
29};
30
31
46template <typename T>
47struct WeakPtr {
49
51 WeakPtr(T* ptr) {
52 set(ptr);
53 }
54 WeakPtr(const WeakPtr& other) {
55 set(other.get());
56 }
57 WeakPtr& operator=(const WeakPtr& other) {
58 set(other.get());
59 return *this;
60 }
62 set(nullptr);
63 }
64 void set(T* ptr) {
65 // Release handle
66 if (weakHandle) {
67 // Decrement and check handle reference count
68 if (--weakHandle->count == 0) {
69 // Remove handle from object and delete it
70 T* oldPtr = reinterpret_cast<T*>(weakHandle->ptr);
71 if (oldPtr) {
72 oldPtr->weakHandle = nullptr;
73 }
74 delete weakHandle;
75 }
76 weakHandle = nullptr;
77 }
78 // Obtain handle
79 if (ptr) {
80 if (!ptr->weakHandle) {
81 // Create new handle for object
82 ptr->weakHandle = new WeakHandle(ptr);
83 }
84 weakHandle = ptr->weakHandle;
85 // Increment handle reference count
87 }
88 }
89 T* get() const {
90 if (!weakHandle)
91 return nullptr;
92 return reinterpret_cast<T*>(weakHandle->ptr);
93 }
94 T* operator->() const {
95 return get();
96 }
97 T& operator*() const {
98 return *get();
99 }
100 operator T*() const {
101 return get();
102 }
103 explicit operator bool() const {
104 return get();
105 }
106};
107
108
109} // namespace rack
Root namespace for the Rack API.
Definition AudioDisplay.hpp:9
Base class for classes that allow WeakPtrs to be used.
Definition weakptr.hpp:16
size_t getWeakCount()
Definition weakptr.hpp:24
~WeakBase()
Definition weakptr.hpp:19
WeakHandle * weakHandle
Definition weakptr.hpp:17
Definition weakptr.hpp:8
size_t count
Definition weakptr.hpp:10
void * ptr
Definition weakptr.hpp:9
WeakHandle(void *ptr)
Definition weakptr.hpp:11
A weak pointer to a subclass of WeakBase.
Definition weakptr.hpp:47
T * get() const
Definition weakptr.hpp:89
void set(T *ptr)
Definition weakptr.hpp:64
T & operator*() const
Definition weakptr.hpp:97
WeakPtr(T *ptr)
Definition weakptr.hpp:51
WeakPtr(const WeakPtr &other)
Definition weakptr.hpp:54
~WeakPtr()
Definition weakptr.hpp:61
WeakPtr()
Definition weakptr.hpp:50
WeakHandle * weakHandle
Definition weakptr.hpp:48
WeakPtr & operator=(const WeakPtr &other)
Definition weakptr.hpp:57
T * operator->() const
Definition weakptr.hpp:94