LeviLamina
Loading...
Searching...
No Matches
WeakPtr.h
1#pragma once
2
3#include "mc/_HeaderOutputPredefine.h"
4#include "mc/common/SharedCounter.h"
5
6template <typename T>
7class SharedPtr;
8
9template <typename T>
10class WeakPtr {
11public:
12 [[nodiscard]] WeakPtr() noexcept : counter(nullptr) {}
13 [[nodiscard]] WeakPtr(std::nullptr_t) noexcept : counter(nullptr) {}
14
15 template <class Y>
16 [[nodiscard]] explicit WeakPtr(SharedPtr<Y> const& other)
17 requires(std::convertible_to<Y*, T*>)
18 {
19 counter = (SharedCounter<T>*)other.counter;
20 if (counter) {
21 counter->addWeakCount();
22 }
23 }
24
25 template <class Y>
26 [[nodiscard]] explicit WeakPtr(WeakPtr<Y> const& other)
27 requires(std::convertible_to<Y*, T*>)
28 {
29 counter = (SharedCounter<T>*)other.counter;
30 if (counter) {
31 counter->addWeakCount();
32 }
33 }
34
35 template <class Y>
36 [[nodiscard]] explicit WeakPtr(WeakPtr<Y>&& other)
37 requires(std::convertible_to<Y*, T*>)
38 {
39 counter = (SharedCounter<T>*)other.counter;
40 other.counter = nullptr;
41 }
42
43 ~WeakPtr() {
44 if (counter) {
45 counter->releaseWeak();
46 }
47 }
48
49 template <class Y>
50 WeakPtr<T>& operator=(SharedPtr<Y> const& other)
51 requires(std::convertible_to<Y*, T*>)
52 {
53 if (counter != (SharedCounter<T>*)other.counter) {
54 counter = (SharedCounter<T>*)other.counter;
55 if (counter) {
56 counter->addWeakCount();
57 }
58 }
59 return *this;
60 }
61
62 template <class Y>
63 WeakPtr<T>& operator=(WeakPtr<Y> const& other)
64 requires(std::convertible_to<Y*, T*>)
65 {
66 if (counter != (SharedCounter<T>*)other.counter) {
67 counter = (SharedCounter<T>*)other.counter;
68 if (counter) {
69 counter->addWeakCount();
70 }
71 }
72 return *this;
73 }
74
75 template <class Y>
76 WeakPtr<T>& operator=(WeakPtr<Y>&& other)
77 requires(std::convertible_to<Y*, T*>)
78 {
79 if (counter != (SharedCounter<T>*)other.counter) {
80 counter = (SharedCounter<T>*)other.counter;
81 other.counter = nullptr;
82 }
83 return *this;
84 }
85
86 [[nodiscard]] int use_count() const { return counter ? counter->getShareCount() : 0; }
87
88 [[nodiscard]] bool expired() const { return use_count() == 0; }
89
90 [[nodiscard]] SharedPtr<T> lock() const { return expired() ? SharedPtr<T>() : SharedPtr<T>(*this); }
91
92 [[nodiscard]] T* get() const { return counter ? counter->get() : nullptr; }
93
94 [[nodiscard]] T* operator->() const { return get(); }
95
96 [[nodiscard]] T& operator*() const { return *get(); }
97
98 [[nodiscard]] explicit operator bool() const { return get() != nullptr; }
99
100 SharedCounter<T>* counter;
101};
Definition SharedCounter.h:6
Definition SharedPtr.h:10
Definition WeakPtr.h:10