Boost库学习—智能指针Shared_ptr学习01
来源:互联网 发布:淘宝卖家会员卡设置 编辑:程序博客网 时间:2024/06/08 08:14
声明:本人属于技术小白,文章中的用词可能不够准确,本人书写文章仅仅是个人记录,不足之处希望大家批评指正,也请阅读本文者谅解!
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
- Boost库学习—智能指针Shared_ptr学习01
- 智能指针Boost.smart_ptr学习4--shared_ptr
- Boost智能指针—shared_ptr
- 学习笔记四:boost智能指针:scoped_ptr和shared_ptr
- 【Boost】boost库中智能指针——shared_ptr
- Boost智能指针:shared_ptr
- 智能指针boost::shared_ptr
- 智能指针boost::shared_ptr
- Boost智能指针:shared_ptr
- 智能指针shared_ptr使用学习
- 【C++学习】智能指针-shared_ptr
- Boost库智能指针学习
- Boost库智能指针学习
- boost库之shared_ptr库,智能指针
- Boost智能指针——shared_ptr
- [转载]Boost智能指针——shared_ptr
- Boost智能指针——shared_ptr
- Boost智能指针——shared_ptr
- 图论算法 最短时间
- Java 高新技术(内省)
- Problem 8:Largest product in a series
- 二进制十进制相互转换
- CoAP学习笔记1--概述
- Boost库学习—智能指针Shared_ptr学习01
- MFC-day01
- 2014年春
- C++中空类的大小
- nyoj 94 cigarettes
- Java 类中各成分加载顺序 和 内存中的存放位置
- travel the binary tree by level 2 ( from top to down )
- largeCommon
- 浅谈“三层架构”