counting smart pointer

#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)) // The parameter pointer is an invalid pointer
{
return *this;
}
if(m_p==NULL||NULL==p_count||0==*p_count) // The assigned pointer does not originally point to the object
{
m_p=p .m_p;
p_count=p.p_count;
(*p_count)++;
}
else
{
if(0==--*p_count) // The assigned pointer count is decreased by 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;
}
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324903567&siteId=291194637
Recommended