Grindstone Game Engine v0.2.0
An open source game engine and toolkit.
Loading...
Searching...
No Matches
SharedPtr.hpp
1#pragma once
2
3namespace Grindstone::Memory::SmartPointers {
4 template<typename T>
5 class SharedPtr {
6 public:
8 unsigned int refCount = 1;
9 };
10
11 SharedPtr() = default;
12
13 SharedPtr(T* ptr, std::function<void(void*)> deleteFn) : ptr(ptr), deleteFn(deleteFn), refCounter(new SharedPtrRefCounter()) {}
14
15 SharedPtr(const SharedPtr& obj) : ptr(obj.ptr), refCounter(obj.refCounter) {
16 if (refCounter) {
17 ++refCounter->refCount;
18 }
19 }
20
21 SharedPtr& operator=(const SharedPtr& obj) {
22 if (ptr && refCounter && --refCounter->refCount == 0) {
23 ptr->~T();
24 deleteFn(ptr);
25 delete refCounter;
26 }
27
28 ptr = obj->ptr;
29 refCounter = obj->refCounter;
30
31 if (ptr && refCounter) {
32 ++refCounter->refCount;
33 }
34 }
35
36 T* operator->() {
37 return this->ptr;
38 }
39
40 T& operator*() {
41 return *(this->ptr);
42 }
43
44 const T* operator->() const {
45 return this->ptr;
46 }
47
48 const T& operator*() const {
49 return *(this->ptr);
50 }
51
52 ~SharedPtr() {
53 if (refCounter != nullptr &&
54 ptr != nullptr &&
55 --refCounter->refCount == 0
56 ) {
57 ptr->~T();
58 deleteFn(ptr);
59 delete refCounter;
60 }
61 }
62
63 private:
64 T* ptr = nullptr;
65 SharedPtrRefCounter* refCounter = nullptr;
66 std::function<void(void*)> deleteFn;
67 };
68
69 template<typename T, typename... Args>
70 SharedPtr<T> MakeShared(Args&&... params) {
71 return new T(std::forward<Args>(params)...);
72 }
73}