Skip to content

Instantly share code, notes, and snippets.

@StarJade-Park
Last active January 6, 2020 10:54
Show Gist options
  • Save StarJade-Park/939ba16c288e0e36a97ba902bca7cdc5 to your computer and use it in GitHub Desktop.
Save StarJade-Park/939ba16c288e0e36a97ba902bca7cdc5 to your computer and use it in GitHub Desktop.
#ifndef __SHARED_PTR_H__
#define __SHARED_PTR_H__
#include "Reference.h"
template<class T>
class shared_ptr
{
public:
shared_ptr()
: m_pObject(nullptr)
{
}
shared_ptr(const std::nullptr_t Pointer)
: m_pObject(Pointer)
{
}
shared_ptr(const T* Pointer)
: m_pObject(Pointer)
{
AddCounter();
}
shared_ptr(const shared_ptr& Other)
: m_pObject(Other.m_pObject)
{
AddCounter();
}
virtual ~shared_ptr()
{
SubtractCounter();
}
T* const operator->( ) const
{
return m_pObject;
}
T& operator*( ) const
{
return (*m_pObject);
}
private:
AddCounter()
{
if(nullptr == m_pObject)
{
return;
}
dynamic_cast<Reference*>(m_pObject)->AddCount();
}
SubtractCounter()
{
if(nullptr == m_pObject)
{
return;
}
dynamic_cast<Reference*>(m_pObject)->SubtractCount();
}
private:
T* m_pObject;
};
#endif // !__SHARED_PTR_H__
// Reference.h
#ifndef __REFERENCE_H__
#define __REFERENCE_H__
class Reference
{
template<typename T>
friend class shared_ptr;
protected:
Reference() = default;
virtual ~Reference() = default;
void AddCount()
{
++m_ReferenceCount;
}
void SubstractCount()
{
--m_ReferenceCount;
if(0 >= m_ReferenceCount)
{
m_ReferenceCount = 0;
delete this;
}
}
private:
unsigned int m_ReferenceCount = 0;
};
#endif // !__REFERENCE_H__
template<class T>
bool operator==(const std::nullptr_t ptr, const shared_ptr<T>& sPtr)
{
return ptr == sPtr.m_pObject;
}
template<class T>
bool operator!=(const std::nullptr_t ptr, const shared_ptr<T>& sPtr)
{
return ptr != sPtr.m_pObject;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment