c++41智能指针

 

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值