计数型智能指针

it2022-05-09  37

#include<iostream>using namespace std;

template <typename T>class my_shared_ptr{public:

my_shared_ptr();my_shared_ptr(T* p);my_shared_ptr(my_shared_ptr<T>& p);my_shared_ptr<T> operator=(my_shared_ptr<T>& p);~my_shared_ptr();void show_cnt(){ if(p_count==NULL||m_p==NULL) { cout<<"nullptr of my_shared_ptr"<<endl; return; } cout<<*p_count<<endl;}

private:

int* p_count;T* m_p;};int main(){ my_shared_ptr<int> p1(new int(100)); p1.show_cnt(); my_shared_ptr<int> p2(p1); p1.show_cnt(); p2.show_cnt(); my_shared_ptr<int> p3; p3=p1; p1.show_cnt(); p2.show_cnt(); p3.show_cnt(); my_shared_ptr<int> p4; cout<<"...."<<endl; my_shared_ptr<int> pB1(new int(200)); my_shared_ptr<int> pB2(pB1); pB1 = p1; p1.show_cnt(); p2.show_cnt(); p3.show_cnt(); pB2.show_cnt(); return 0;}

template <typename T>my_shared_ptr<T>::my_shared_ptr(){ p_count = NULL; m_p = NULL;}

template <typename T>my_shared_ptr<T>::my_shared_ptr(T* p){ if(NULL!=p) { p_count = new int(1); m_p = p; p=NULL; }}

template <typename T>my_shared_ptr<T>::my_shared_ptr(my_shared_ptr<T>& p) // copy construct{ if(NULL==p.m_p||NULL==p.p_count||0==*(p.p_count)) { m_p=NULL; p_count = NULL; return; } m_p = p.m_p; p_count = p.p_count; (*p_count)++;}

template <typename T>my_shared_ptr<T> my_shared_ptr<T>::operator=(my_shared_ptr<T>& p){ if(NULL==p.m_p||NULL==p.p_count||0==*(p.p_count)) // 参数指针是个无效指针 { return *this; } if(m_p==NULL||NULL==p_count||0==*p_count) // 被赋值指针原本不指向对象 { m_p=p.m_p; p_count=p.p_count; (*p_count)++; } else { if(0==--*p_count) // 被赋值指针计数减少1 { delete p_count; delete m_p; p_count=NULL; m_p = NULL; } p_count = p.p_count; m_p = p.m_p; ++*p_count; } return *this;}

template <typename T>my_shared_ptr<T>::~my_shared_ptr(){ if(p_count!=NULL||m_p!= NULL) { (*p_count)--; if(*p_count==0) { delete m_p; } m_p=NULL; }}

转载于:https://www.cnblogs.com/fchy822/p/8944261.html


最新回复(0)