#ifndef SHARED_PTR_H
#define SHARED_PTR_H
#include <stdio.h>
#include <iostream>
using namespace std;
template <typename T> // 泛型编程
class Shared_ptr
{
public:
Shared_ptr(T* ptr = nullptr) : m_ptr(ptr)
{
if(m_ptr)
{
m_cnt = new int(1);
}
}
~Shared_ptr()
{
if (--(*m_cnt) == 0)
{
delete m_ptr;
m_ptr = nullptr;
delete m_cnt;
m_cnt = nullptr;
}
}
Shared_ptr(const Shared_ptr& ptr)
{
if (this != ptr)
{
m_cnt = ptr.m_cnt;
m_ptr = ptr.m_ptr;
++(*m_cnt);
}
}
Shared_ptr& operator=(Shared_ptr& share_ptr)
{
++*(share_ptr->m_cnt); // 等式右边引用次数加一
if (m_ptr && 0 == --(*m_cnt)) //左边引用次数减一,当左边引用次数为零时清除左边的资源
{
delete m_cnt;
m_cnt = nullptr;
delete m_ptr;
m_ptr = nullptr;
}
m_ptr = share_ptr.m_ptr;
m_cnt = share_ptr.m_cnt; //使它们指向同一个地址空间,实现数据共享
return *this;
}
T& operator*()
{
return *m_ptr;
}
T* operator->()
{
return m_ptr;
}
private:
T* m_ptr;
size_t* m_cnt; //指针,才能被共享
};