#pragma once
template<class T>
class SharedPointer
{
public:
SharedPointer():m_refCount(nullptr), m_pointer(nullptr){}
SharedPointer(T* adoptTarget):m_pointer(adoptTarget), m_refCount(nullptr)
{
addReference();
}
SharedPointer(const SharedPointer<T>& copy)
:m_refCount(copy.m_refCount),m_pointer(copy.m_pointer)
{
addReference();
}
virtual ~SharedPointer()
{
removeReference();
}
SharedPointer<T>& operator=(const SharedPointer<T>& that)
{
if(this != &that)
{
removeReference();
this->m_pointer = that.m_pointer;
this->m_refCount = that.m_refCount;
addReference();
}
return *this;
}
bool operator==(const SharedPointer<T>& that)
{
return this->m_pointer == that->m_pointer;
}
bool operator!=(const SharedPointer<T>& that)
{
return !operator==(that);
}
T& operator*() const
{
return *m_pointer;
}
T* operator->() const
{
return m_pointer;
}
int GetReferenceCount() const
{
if(nullptr != m_refCount)
{
return (*m_refCount);
}
else
{
return -1;
}
}
protected:
void addReference()
{
if(nullptr != m_refCount)
{
(*m_refCount)++;
}
else
{
m_refCount = new int(0);
*m_refCount = 1;
}
}
void removeReference()
{
if(nullptr != m_refCount)
{
(*m_refCount)--;
if(0 == (*m_refCount))
{
delete m_refCount;
delete m_pointer;
m_pointer = nullptr;
m_refCount = nullptr;
}
}
}
private:
int* m_refCount;
T* m_pointer;
};
shared_ptr简单实现