#include<iostream>
#include<cstdio>
using namespace std;
template<typename T>
class SmartPointer
{
public:
SmartPointer(T* ptr)
{
ref=ptr;
ref_count=(unsigned int*) malloc(sizeof(unsigned));
*ref_count=1;
}
SmartPointer(const SmartPointer<T>& other)
{
ref=other.ref;
ref_count=other.ref_count;
++*ref_count;
}
SmartPointer& operator=(SmartPointer<T>& other)
{
if(this==&other)
return *this;
if(--*ref_count==0)
{
clear();
}
ref=other.ref;
ref_count=other.ref_count;
++*ref_count;
return *this;
}
T& operator*()
{
return *ref;
}
T* operator->()
{
return ref;
}
~SmartPointer()
{
if(--*ref_count==0)
{
clear();
}
}
private:
void clear()
{
delete ref;
free(ref_count);
ref=NULL;
ref_count=NULL;
}
protected:
T* ref;
unsigned int* ref_count;
};
void main()
{
int* p=new int();
*p=11;
SmartPointer<int> ptr1(p);
SmartPointer<int> ptr2=ptr1;
*ptr1=1;
cout<<*ptr1<<" "<<*ptr2<<endl;
}