#include<iostream>
template<class T>
class SmartPtr
{
public:
SmartPtr(T* ptr):_ptr(ptr)
{}
~SmartPtr()
{
if(_ptr)
{
std::cout<<"释放成功"<<std::endl;
delete _ptr;
}
}
T& operator*()
{
return *_ptr;
}
T* operator->()
{
return _ptr;
}
private:
T * _ptr;
};
#include <iostream>
#include<vector>
#include"SmartPtr.h"
using namespace std;
/************************
c++ 没有gc,new/malloc出来的资源,是需要我们去手动释放
1.忘记释放
2.发生异常安全问题
*************************/
int div()
{
int a= 3, b =0;
if(b==0) throw invalid_argument("除0错误");
return a/b;
}
void f1()
{
int *p = new int;
SmartPtr <int> sp(p);
s
div();
}
void test01()
{
try{
f1();
}catch(exception &e)
{
cout<<e.what()<<endl;
}
}
/*************************************
c++98 auto_ptr 管理权转移
c++11 unique_ptr 防拷贝
c++11 shared_ptr 引用计数的共享拷贝
*********************************************/
int main()
{
test01();
return 0;
}