SleakEngine 1.0.0
C++23 multi-backend game engine
Loading...
Searching...
No Matches
WeakPtr.hpp
Go to the documentation of this file.
1#ifndef _WEAK_PTR_H_
2#define _WEAK_PTR_H_
3
4#include "RefPtr.hpp"
5
6namespace Sleak {
7
8 /// Non-owning observer of a RefPtr-managed object; lock() to get a strong
9 /// reference back, or check expired() before touching the raw pointer.
10 /// @ingroup memory
11 template <typename T>
12 class WeakPtr {
13 private:
14 T* ptr; // Raw pointer to the observed object
15 size_t* refCount; // Pointer to the reference count
16
17 public:
18 // Default constructor
19 WeakPtr() : ptr(nullptr), refCount(nullptr) {}
20
21 // Constructor from RefPtr
22 WeakPtr(const RefPtr<T>& refPtr)
23 : ptr(refPtr.get()), refCount(refPtr.refCount) {}
24
25 // Copy constructor
26 WeakPtr(const WeakPtr& other)
27 : ptr(other.ptr), refCount(other.refCount) {}
28
29 // Destructor
30 ~WeakPtr() = default;
31
32 // Copy assignment
33 WeakPtr& operator=(const WeakPtr& other) {
34 if (this != &other) {
35 ptr = other.ptr;
36 refCount = other.refCount;
37 }
38 return *this;
39 }
40
41 // Assignment from RefPtr
42 WeakPtr& operator=(const RefPtr<T>& refPtr) {
43 ptr = refPtr.get();
44 refCount = refPtr.refCount;
45 return *this;
46 }
47
48 // Lock the WeakPtr to create a RefPtr
49 RefPtr<T> lock() const {
50 if (refCount && *refCount > 0) {
51 return RefPtr<T>(*this);
52 }
53 return RefPtr<T>();
54 }
55
56 // Check if the object is still valid
57 bool expired() const {
58 return !refCount || *refCount == 0;
59 }
60
61 // Get the reference count
62 size_t use_count() const {
63 return refCount ? *refCount : 0;
64 }
65 };
66
67} // namespace Sleak
68
69#endif // _WEAK_PTR_H_
T * get() const
Definition RefPtr.hpp:170
RefPtr< T > lock() const
Definition WeakPtr.hpp:49
WeakPtr & operator=(const RefPtr< T > &refPtr)
Definition WeakPtr.hpp:42
bool expired() const
Definition WeakPtr.hpp:57
~WeakPtr()=default
WeakPtr & operator=(const WeakPtr &other)
Definition WeakPtr.hpp:33
WeakPtr(const RefPtr< T > &refPtr)
Definition WeakPtr.hpp:22
WeakPtr(const WeakPtr &other)
Definition WeakPtr.hpp:26
size_t use_count() const
Definition WeakPtr.hpp:62
Root namespace for everything the engine exposes.
Definition Camera.hpp:10