shared_ptr 智能指针 极简火速入门



综述:

    new的方式,众所皆知,申请的空间在堆区,需要自己释放,而智能指针,通过系统维护,虽然也在堆区申请可空间,但是无需自己释放,从而完全避免了因忘记释放而造成的内存泄露,故墙裂建议用new的地方全部换成shared_ptr。


注:shared_ptr主要用于对象,以下示例代码用int和string是为了方便。


#include <tr1/memory>                                                                                 
#include <iostream>


using namespace std;

int main()
{
    //  职能指针 用法一
    tr1::shared_ptr<int> tmp(new int(35));
    cout<<"shared_ptr init 1:"<<(*tmp)<<endl;


    //  智能指针 用法二
    tr1::shared_ptr<int> tmp2;
    tmp2.reset(new int(15));      //  可用于赋新值

    cout<<"shared_ptr init 2:"<<(*(tmp2.get()))<<endl;   // get用于获取常规指针,get返回值等同于用new申请变量的指针


    //  智能指针 用法三
    tr1::shared_ptr<string> tmp3(new string("hello world"));
    cout<<"try to use reset() to blank the shared_ptr--befor:"<<(*tmp3)<<"\t"<<(*(tmp3.get()))<<endl;
    tmp3.reset();
    cout<<"try to use reset() to blank the shared_ptr--after:";
    if(tmp3 == NULL )
        cout<<"shared_ptr is NULL"<<endl;
    else
        cout<<"shared_ptr is not NULL"<<(*tmp3)<<endl;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值