From 3b4c16d7ca1d1e77cdf86520ece2c8e97d3f66e9 Mon Sep 17 00:00:00 2001 From: jakcron Date: Sun, 23 Sep 2018 11:27:42 +0800 Subject: [PATCH] [fnd] Add SharedPtr template class. --- lib/libfnd/include/fnd/SharedPtr.h | 141 +++++++++++++++++++++++++++++ 1 file changed, 141 insertions(+) create mode 100644 lib/libfnd/include/fnd/SharedPtr.h diff --git a/lib/libfnd/include/fnd/SharedPtr.h b/lib/libfnd/include/fnd/SharedPtr.h new file mode 100644 index 0000000..e976d4e --- /dev/null +++ b/lib/libfnd/include/fnd/SharedPtr.h @@ -0,0 +1,141 @@ +#pragma once +#include +#include + +namespace fnd +{ + template + class SharedPtr + { + public: + SharedPtr(); + + // constructor for creating owner object + SharedPtr(T* ptr); + + // copy constructor + SharedPtr(const SharedPtr& other); + + // destructor + ~SharedPtr(); + + // own operator + void operator=(T* ptr); + + // copy operator + void operator=(const SharedPtr& other); + + // access ptr + const T* operator*() const; + T* operator*(); + + private: + T* mPtr; + size_t* mRefCnt; + + void deletePtr(); + }; + + template + inline SharedPtr::SharedPtr() : + mPtr(nullptr), + mRefCnt(new size_t) + { + *mRefCnt = 0; + } + + template + inline SharedPtr::SharedPtr(T* ptr) : + SharedPtr() + { + *this = ptr; + } + + template + inline SharedPtr::SharedPtr(const SharedPtr& other) : + SharedPtr() + { + *this = other; + } + + template + inline SharedPtr::~SharedPtr() + { + deletePtr(); + } + + template + inline void SharedPtr::operator=(T* ptr) + { + deletePtr(); + if (ptr != nullptr) + { + mPtr = ptr; + mRefCnt = new size_t; + *mRefCnt = 1; + } + else + { + mPtr = nullptr; + mRefCnt = new size_t; + *mRefCnt = 0; + } + + } + + template + inline void SharedPtr::operator=(const SharedPtr& other) + { + deletePtr(); + + mPtr = other.mPtr; + mRefCnt = other.mRefCnt; + *mRefCnt += 1; + } + + template + inline const T* SharedPtr::operator*() const + { + return mPtr; + } + + template + inline T* SharedPtr::operator*() + { + return mPtr; + } + + template + inline void SharedPtr::deletePtr() + { + // if this is not the last reference + if (*mRefCnt > 1) + { + // decrement reference count + *mRefCnt -= 1; + + // make ptrs null + mPtr = nullptr; + mRefCnt = nullptr; + } + // if this is the last refeference + else if (*mRefCnt == 1) + { + // delete memory + delete mPtr; + delete mRefCnt; + + // make ptrs null + mPtr = nullptr; + mRefCnt = nullptr; + } + // else if this is an empty refernce + else if (*mRefCnt == 0) + { + delete mRefCnt; + + mPtr = nullptr; + mRefCnt = nullptr; + } + } +} \ No newline at end of file