声明:本人属于技术小白,文章中的用词可能不够准确,本人书写文章仅仅是个人记录,不足之处希望大家批评指正,也请阅读本文者谅解!
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; }
结果还是很明显的,虽然占用了一点空间,但内存还是不断被释放掉了。