SharedPtr定义
//shared_ptr
template<typename T>
class SharedPtr{
public:
SharedPtr(T* p = NULL):m_ptr(p){
if (NULL != p){
pm_count = new int(1);
cout<<"create: m_ptr(*p = null). count = 1."<<endl;
} else {
pm_count = new int(0);
cout<<"create: m_ptr(*p != null). count = 0."<<endl;
}
}
SharedPtr(SharedPtr<T>& p){
if (this != &p){
this->m_ptr = p.m_ptr;
this->pm_count = p.pm_count;
++(*this->pm_count);
cout<<"create: m_ptr(&p). count = "<<*pm_count<<endl;
}
}
SharedPtr& operator=(SharedPtr<T>& p){
if (this != &p){
cout<<"operator =: this != p old count = "<<*pm_count<<endl;
--(*pm_count);
if (0 == *pm_count){
delete m_ptr;
delete pm_count;
}
m_ptr = p.m_ptr;
pm_count = p.pm_count;
++(*pm_count);
cout<<"operator =: this != p new count = "<<*pm_count<<endl;
}else{
cout<<"operator =: this == p "<<endl;
}
return *this;
}
~SharedPtr(){
if (NULL != m_ptr ){
cout<<"delete: m_ptr is not null. count = "<<*pm_count<<endl;
--(*pm_count);
if (0 == *pm_count){
cout<<"delete: count is 0 "<<endl;
delete m_ptr;
delete pm_count;
}else{
cout<<"delete: count!= 0; count = "<<*pm_count<<endl;
}
}else{
cout<<"delete: m_ptr is null."<<endl;
}
}
T& operator*(){
return *m_ptr;
}
T* operator->(){
return m_ptr;
}
protected:
T* m_ptr;
int *pm_count;
};
测试代码
int main()
{
cout<<"Test start."<<endl;
SharedPtr<int> p1(new int(100));
SharedPtr<int> p2(p1);
SharedPtr<int> p3(p2);
p1 = p2;
p1 = p3;
p3 = p3;
return 0;
}