#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;
//指针指向NULL(0x00)
m_pointer = nullptr;
m_refCount = nullptr;
}
}
}
private:
int* m_refCount; //引用计数
T* m_pointer; //原始指针
};
shared_ptr的简单实现
最新推荐文章于 2024-07-24 11:32:27 发布