#include <iostream>
using namespace std;
class Test
{
public:
Test()=default;
Test(int a):a(a)
{
cout << "Test有参构造函数\n";
}
virtual ~Test()
{
cout << "Test 析构函数\n";
}
void show()
{
cout << "a=" << a <<endl;
}
private:
int a;
};
template<class T>
class Smartptr
{
public:
Smartptr(T* p=0):myptr(p)
{
cout << "Smartptr有参构造函数\n";
}
virtual ~Smartptr()
{
if(nullptr!=myptr)
delete myptr;
myptr=nullptr;
cout << "Smartptr 析构函数\n";
}
//拷贝构造
Smartptr(Smartptr<T> &other)
{
myptr=other.myptr;
other.myptr=nullptr;
}
//拷贝赋值
Smartptr<T>& operator=(Smartptr<T>& other)
{
if(myptr!=other.myptr)
{
myptr=other.myptr;
}
other.myptr=nullptr;
return *this;
}
T* get()
{
return myptr;
}
T* release()
{
T* p=myptr;
myptr=nullptr;
return p;
}
void reset(T* p=0)
{
if(myptr!=nullptr)
{
delete myptr;
}
myptr=p;
}
T*& operator->()
{
return myptr;
}
T& operator*()
{
return *myptr;
}
private:
T* myptr;
};
int main(int argc, const char *argv[])
{
Test* t1=new Test(10);
Test* t2=new Test(20);
t1->show();
t2->show();
cout << "**********************\n";
Smartptr<Test> p1(t1);
p1->show();
(*p1).show();
cout << "**********************\n";
Smartptr<Test> p2=p1;
p2->show();
//pt1->show();
cout << "**********************\n";
Smartptr<Test> p3;
p3=p2;
//pt2->show();
p3->show();
p3.reset(t2);
p3->show();
p3.release();
//p3->show();
cout << "**********************\n";
return 0;
}