Smart Pointer
#include "stdafx.h"
#include <iostream>
using namespace std;
class emp
{
private:
int age;
char* name;
public:
emp() : age(0),name(0)
{
}
emp(int p_age, char* p_name) : age(p_age) , name(p_name)
{
}
void display()
{
cout<<"Age=" << age << "\n" << "Name=" << name <<"\n";
}
};
class Student
{
private:
int age;
char* name;
public:
Student() : age(0),name(0)
{
}
Student(int p_age, char* p_name) : age(p_age) , name(p_name)
{
}
Student(const Student& obj)
{
this->age = obj.age;
this->name = obj.name;
}
Student* operator= (const Student& obj)
{
this->age = obj.age;
this->name = obj.name;
return this;
}
void display()
{
cout<<"Student_Age=" << age << "\n" << "Student_Name=" << name <<"\n";
}
};
class RC
{
private:
int count;
public:
void Addref()
{
count++;
}
int ReleaseRef()
{
return --count;
}
};
template <typename T> class SP
{
private:
T* p_emp;
RC* Referenace;
public:
SP() : p_emp(0), Referenace(0)
{
Referenace = new RC();
Referenace->Addref();
}
SP(T* t_emp) : p_emp(t_emp) , Referenace(0)
{
Referenace = new RC();
Referenace->Addref();
}
SP(const SP<T>& sp) : p_emp(sp.p_emp) , Referenace(sp.Referenace)
{
Referenace->Addref();
}
SP<T>& operator=(const SP<T>& sp)
{
if(this != &sp)
{
if(Referenace->ReleaseRef() == 0)
{
delete p_emp;
delete Referenace;
}
p_emp = sp.p_emp;
Referenace = sp.Referenace;
Referenace->Addref();
}
return *this;
}
T& operator*()
{
return *p_emp;
}
T* operator->()
{
return p_emp;
}
~SP()
{
if(Referenace->ReleaseRef() == 0)
{
delete p_emp;
delete Referenace;
}
}
};
int _tmain(int argc, _TCHAR* argv[])
{
/*emp* amp_ptr = new emp(23,"Goudham");
amp_ptr->display();*/
Student ptr(60,"Stuededkjhckshdf");
Student ptr1;
ptr1 = (ptr);
SP<emp> obj(new emp(25,"Goudham"));
obj->display();
{
SP<emp> obj2;
obj2 = obj;
obj2->display();
}
obj->display();
SP<Student> s_obj(new Student(35,"King"));
s_obj->display();
SP<Student> s_obj2(s_obj);
s_obj2->display();
return 0;
}
Comments
Post a Comment