| 45 | */ |
| 46 | template <typename T> |
| 47 | struct WeakPtr { |
| 48 | WeakHandle* weakHandle = NULL; |
| 49 | |
| 50 | WeakPtr() {} |
| 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 | } |
| 61 | ~WeakPtr() { |
| 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 |
| 86 | weakHandle->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(); |