Boost库学习—智能指针Shared_ptr学习01

声明:本人属于技术小白,文章中的用词可能不够准确,本人书写文章仅仅是个人记录,不足之处希望大家批评指正,也请阅读本文者谅解!


Boost库学习—智能指针Shared_ptr学习01

文档目的:本文想简单的介绍一下Shared_ptr智能指针确实可以自动释放掉分配的内存。

操作环境:操作系统windows XP、开发工具VS2005、Boost库

太专业的东西我恐怕也讲不了,我就贴两个小例子,来说明一下自己用到的体会吧。


        首先我写了一个使用new分配一个内存,但是又不使用delete回收掉内存的例子,该例子确实有问题,但确实能看到内存泄露的现象。

#include <windows.h>
#include <stdio.h>
#include <string>
#include <assert.h>
#include <iostream>
#include <iterator>
#include <algorithm>
#include <vector>
#include <boost/smart_ptr.hpp>
using namespace std;
using std::cout;
using std::endl;
using std::cin;

typedef boost::shared_ptr<double> IntPtr;

void ZhdPtest()
{
    double *m_pInt = new double(10);
    double *m_pInt_two;
    m_pInt_two = m_pInt;
    printf("the m_pInt is %d\n", m_pInt);
    printf("the m_pInt_two is %d\n", m_pInt_two);
}

int main()
{ 
    for(int i = 0; i < 3; i++ )
    {
        ZhdPtest();
    }

    getchar();
    return 0;
}
        运行后结果如下图所示:

        从该图中我们可以看出,我打印出的分配的地址信息是在不断增加的,所以可以确定内存在不断的占用没有释放掉。


        接下来,我开始使用Shared_ptr智能指针,代码如下:

#include <windows.h>
#include <stdio.h>
#include <string>
#include <assert.h>
#include <iostream>
#include <iterator>
#include <algorithm>
#include <vector>
#include <boost/smart_ptr.hpp>
using namespace std;
using std::cout;
using std::endl;
using std::cin;

typedef boost::shared_ptr<double> IntPtr;

void ZhdTest()
{
    IntPtr m_pInt(new double(10));

    IntPtr m_pInt_two;
    m_pInt_two = m_pInt;

    printf ( "the m_pInt's number is %d\n",  m_pInt);
    printf ( "the m_pInt_two's number is %d\n",  m_pInt_two);
}

int main()
{ 
    for(int i = 0; i < 3; i++ )
    {
        ZhdTest();
    }

    getchar();
    return 0;
}
        运行后的结果如下图所示:

        结果还是很明显的,虽然占用了一点空间,但内存还是不断被释放掉了。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值