梳理智能指针实现功能:
1.创建对象——构造函数
2.回收对象——析构函数
3.拷贝构造
4.赋值重载操作符
5.引用计数(智能指针引用计数是线程安全的,我们实现的话可以使用atomic原子访问)
6.get方法
#include<iostream>
using namespace std;
#include<memory>
class AAAA{
private:
string s;
public:
AAAA(const string str)
{
s = str;
cout<<"AAAA:"<< s << endl;
}
~AAAA()
{
cout<<"~AAAA" << endl;
}
void say()
{
cout<<"say:"<< s << endl;
}
};
#include<atomic>
template<typename T>
//空间指针和引用计数的捆绑关系
struct Node
{
Node(T* _ptr)
{
//接收外面来的空间
ptr = _ptr;
nCount = 1;
}
~Node()
{
//要回收空间
delete ptr;
nCount = 0;
}
T* ptr;
//int nCount;
atomic<int>nCount;
};
template<typename T>
class MyShared_ptr
{
public:
//有参构造 正常使用是第一个指向这个空间的
MyShared_ptr(T* _ptr)
{
m_ptr_count = new Node<T>( _ptr);
}
//拷贝构造 用已有对象来初始化该对象
MyShared_ptr(const MyShared_ptr& _ptr)
{
m_ptr_count = _ptr.m_ptr_count;
(m_ptr_count->nCount)++;
}
//析构 该对象回收 引用计数-1 如果归0 要回收空间
~MyShared_ptr()
{
if(m_ptr_count)
(m_ptr_count->nCount)--;
if(m_ptr_count->nCount == 0)
{
delete m_ptr_count;
m_ptr_count = nullptr;
}
}
//赋值操作符 原空间引用计数-1 如果归0 要回收空间 新空间引用计数+1
const MyShared_ptr& operator = (const MyShared_ptr& _ptr)
{
if(this == &_ptr)return *this;//自己不能给自己赋值
if(m_ptr_count)
{
(m_ptr_count->nCount)--;
if(m_ptr_count->nCount == 0)
{
delete m_ptr_count;
}
m_ptr_count = _ptr.m_ptr_count;
(m_ptr_count->nCount)++;
}
return *this;
}
//get()
T* get()
{
if(m_ptr_count)
return m_ptr_count->ptr;
return nullptr;
}
//引用计数
int use_count()
{
if(m_ptr_count)
return m_ptr_count->nCount.load();
return 0;
}
private:
Node<T>* m_ptr_count;
};
int main()
{
{
MyShared_ptr<AAA1A>spa(new AAAA("my shared_ptr a"));
{
//MyShared_ptr<AAAA>spb(new AAAA("my shared_ptr b"));
MyShared_ptr<AAAA>spb = new AAAA("my shared_ptr b");
spa = spb;
cout<<"a use count:"<<spa.use_count()<<endl;
}
cout<<"a use count:"<<spa.use_count()<<endl;
}
return 0;
}