shared_ptr的实现
shared_ptr
共享指针是用来管理一块堆内存空间的,并且拷贝复制,拷贝赋值都要仍然指向同一个管理的内存,在shared_ptr对象超出其作用域或者死亡的时候调用析构函数根据引用计数来判断是否需要释放管理的堆空间。
我们以一个整型类型为例。
/******************************************************************************
#include <iostream>
#include <memory>
#include<atomic>
using namespace std;
struct RefCount{
atomic<int> _count;
RefCount(){
_count=1;
}
};
class mshared_ptr{
private:
int *p;
RefCount* p_ref;
public:
mshared_ptr(){p=nullptr;p_ref=nullptr;};
mshared_ptr(int *pp){
p=pp;
p_ref=new RefCount();
}
mshared_ptr(const mshared_ptr&msp){
p=msp.p;
p_ref=msp.p_ref;
p_ref->_count++;
}
RefCount* getref()const
{
return p_ref;
}
mshared_ptr& operator=(const mshared_ptr&msp)
{
if(this!=&msp)
{
if(p!=nullptr)
{
p_ref->_count--;
}
p=msp.p;
p_ref=msp.p_ref;
p_ref->_count++;
}
return *this;
}
~mshared_ptr(){
if(--p_ref->_count==0){
cout<<"引用计数为0"<<endl;
delete p;
}
cout<<"析构函数"<<endl;
}
};
int main(){
int *p=new int;
mshared_ptr ptr(p);
mshared_ptr ptr2(ptr);
cout<<ptr.getref()->_count<<endl;
mshared_ptr ptr3;
ptr3=ptr2;
mshared_ptr *ptr4=new mshared_ptr(ptr3);
cout<<ptr.getref()->_count<<endl;
delete ptr4;
return 0;
}
运行结果