智能指针

一、为什么要引入智能指针?


    我们知道,C++中的动态内存需要用户自己来维护,动态开辟的空间,在出函数作用域或者程序正常退出前必须释放掉,否则会造成内存泄露,虽然有时我们已经非常谨慎了,然而当代吗比较长或比较复杂时,我们仍然可能忘记释放,正所谓防不胜防,一起看一段代码:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. void FunTest1()  
  2. {  
  3.     int *p = new int[10];  
  4.     FILE* pFile = fopen( "1.txt""r" );//已读的方式打开"1.txt"文件  
  5.     if (pFile == NULL)//如果打开失败,则返回  
  6.     {  
  7.         return;//error:如果打开失败,则造成内存泄漏  
  8.     }  
  9.     // DoSomethint();  
  10.     if (p != NULL)  
  11.     {  
  12.         delete[] p;  
  13.         p = NULL;  
  14.     }  
  15. }  
  16. void FunTest2()  
  17. {  
  18.     int *p = new int[10];  
  19.     try  
  20.     {  
  21.         //DoSomething();  
  22.     }  
  23.     catch (...)  
  24.     {  
  25.         return;//返回之前忘记释放内存,导致内存泄漏  
  26.     }  
  27.     delete[] p;  
  28. }  

    从上述两个例子中可以看出,在动态申请空间中,每一次返回之前都必须对动态内存进行释放,否则就内存泄漏,这样做不仅麻烦,还容易忘记,那么,怎样解决上述问题呢?就不得不引入我们的新概念---->智能指针(auto_ptr)


 

二、智能指针的基本情况


 1、资源分配即初始化RAII(Resource Acquisition Is Initialization):定义一个类来封装资源的分配和释放,在构造函数完成资源的分配和初始化,在析构函数完成资源的清理,可以保证资源的正确初始化和释放


 2、Boost库的智能指针 

(ps:新的C++11标准中已经引入了unique_ptr/shared_ptr/weak_ptr)



 三、模拟实现库中的某些智能指针 


1、新库中的智能指针---->auto_ptr 

(1)单纯管理空间

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. template <typename T>  
  2. class AutoPtr  
  3. {  
  4. public:  
  5.     AutoPtr(T* ap)  
  6.         :_p(ap)  
  7.     {  
  8.         ap = NULL;//让ap与动态申请的空间脱离关系  
  9.         cout<<"AutoPtr()"<<endl;  
  10.     }  
  11.     ~AutoPtr()  
  12.     {  
  13.         cout<<"~AutoPtr()"<<endl;  
  14.         if(NULL != _p)  
  15.         {  
  16.             delete _p;  
  17.             _p = NULL;  
  18.         }  
  19.     }  
  20. private:  
  21.     T* _p;  
  22. };  
  23. void Funtest()  
  24. {  
  25.     AutoPtr<int> p = new int;  
  26. }  
  27. int main()  
  28. {  
  29.     Funtest();  
  30.     system("pause");  
  31.     return 0;  
  32. }  


运行结果:



(2)拷贝对象

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. template <typename T>  
  2. class AutoPtr  
  3. {  
  4. public:  
  5.     AutoPtr(T* ap)  
  6.         :_p(ap)  
  7.     {  
  8.         ap = NULL;//让ap与动态申请的空间脱离关系  
  9.         cout<<"AutoPtr()"<<endl;  
  10.     }  
  11.     ~AutoPtr()  
  12.     {  
  13.         if(NULL != _p)  
  14.         {  
  15.             cout<<"~AutoPtr()"<<endl;  
  16.             delete _p;  
  17.             _p = NULL;  
  18.         }  
  19.     }  
  20. private:  
  21.     T* _p;  
  22. };  
  23. void Funtest()  
  24. {  
  25.     AutoPtr<int> p = new int;  
  26.     AutoPtr<int> p1(p);  
  27. }  
  28. int main()  
  29. {  
  30.     Funtest();  
  31.     system("pause");  
  32.     return 0;  
  33. }  
ERROR:同一块被释放了两次,导致程序崩溃。 


改进:添加拷贝构造函数

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. template <typename T>  
  2. class AutoPtr  
  3. {  
  4. public:  
  5.     AutoPtr(T* ap)  
  6.         :_p(ap)  
  7.     {  
  8.         ap = NULL;//让ap与动态申请的空间脱离关系  
  9.         cout<<"AutoPtr()"<<endl;  
  10.     }  
  11.     AutoPtr(AutoPtr<T>& ap)//由于内部要改变ap的值,所以去掉const修饰  
  12.         :_p(ap._p)  
  13.     {  
  14.         ap = NULL;//让ap与动态申请的空间脱离关系  
  15.     }  
  16.     ~AutoPtr()  
  17.     {  
  18.         if(NULL != _p)  
  19.         {  
  20.             cout<<"~AutoPtr()"<<endl;  
  21.             delete _p;  
  22.             _p = NULL;  
  23.         }  
  24.     }  
  25. private:  
  26.     T* _p;  
  27. };  
  28. void Funtest()  
  29. {  
  30.     AutoPtr<int> p = new int;  
  31.     AutoPtr<int> p1(p);  
  32. }  
  33. int main()  
  34. {  
  35.     Funtest();  
  36.     system("pause");  
  37.     return 0;  
  38. }  


运行结果:



(3)构造函数的参数要给缺省值

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. template <typename T>  
  2. class AutoPtr  
  3. {  
  4. public:  
  5.     AutoPtr(T* ap)  
  6.         :_p(ap)  
  7.     {  
  8.         ap = NULL;//让ap与动态申请的空间脱离关系  
  9.         cout<<"AutoPtr()"<<endl;  
  10.     }  
  11.     AutoPtr(AutoPtr<T>& ap)//由于内部要改变ap的值,所以去掉const修饰  
  12.         :_p(ap._p)  
  13.     {  
  14.         ap = NULL;//让ap与动态申请的空间脱离关系  
  15.     }  
  16.     ~AutoPtr()  
  17.     {  
  18.         if(NULL != _p)  
  19.         {  
  20.             cout<<"~AutoPtr()"<<endl;  
  21.             delete _p;  
  22.             _p = NULL;  
  23.         }  
  24.     }  
  25. private:  
  26.     T* _p;  
  27. };  
  28. void Funtest()  
  29. {  
  30.     AutoPtr<int> p = new int;  
  31.     AutoPtr<int> p1(p);  
  32.     AutoPtr<int> p2;  
  33. }  
  34. int main()  
  35. {  
  36.     Funtest();  
  37.     system("pause");  
  38.     return 0;  
  39. }  


error:



改进:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. template <typename T>  
  2. class AutoPtr  
  3. {  
  4. public:  
  5.     AutoPtr(T* ap <span style="color:#ff0000;">= NULL</span>)  
  6.         :_p(ap)  
  7.     {  
  8.         ap = NULL;//让ap与动态申请的空间脱离关系  
  9.         cout<<"AutoPtr()"<<endl;  
  10.     }  
  11.     AutoPtr(AutoPtr<T>& ap)//由于内部要改变ap的值,所以去掉const修饰  
  12.         :_p(ap._p)  
  13.     {  
  14.         ap = NULL;//让ap与动态申请的空间脱离关系  
  15.     }  
  16.     ~AutoPtr()  
  17.     {  
  18.         if(NULL != _p)  
  19.         {  
  20.             cout<<"~AutoPtr()"<<endl;  
  21.             delete _p;  
  22.             _p = NULL;  
  23.         }  
  24.     }  
  25. private:  
  26.     T* _p;  
  27. };  
  28. void Funtest()  
  29. {  
  30.     AutoPtr<int> p = new int;  
  31.     AutoPtr<int> p1(p);  
  32.     AutoPtr<int> p2;  
  33. }  
  34. int main()  
  35. {  
  36.     Funtest();  
  37.     system("pause");  
  38.     return 0;  
  39. }  

(4)赋值运算符重载

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. template <typename T>  
  2. class AutoPtr  
  3. {  
  4. public:  
  5.     AutoPtr(T* ap = NULL)  
  6.         :_p(ap)  
  7.     {  
  8.         cout<<"AutoPtr()"<<endl;  
  9.     }  
  10.   
  11.     AutoPtr(AutoPtr<T>& ap)//由于内部要改变ap的值,所以去掉const修饰  
  12.         :_p(ap._p)  
  13.     {  
  14.         ap._p = NULL;//让ap与动态申请的空间脱离关系  
  15.     }  
  16.   
  17.     AutoPtr<T>& operator=(AutoPtr<T>& ap)  
  18.     {  
  19.         if(this != &ap)  
  20.         {  
  21.             if(NULL != _p)//防止对空对象进行引用导致程序崩溃  
  22.             {  
  23.                 delete _p;  
  24.                 _p = ap._p;//如果_p为空,则崩溃  
  25.                 ap._p = NULL;//脱离关系  
  26.             }  
  27.         }  
  28.         return *this;  
  29.     }  
  30.   
  31.     ~AutoPtr()  
  32.     {  
  33.         if(NULL != _p)  
  34.         {  
  35.             cout<<"~AutoPtr()"<<endl;  
  36.             delete _p;  
  37.             _p = NULL;  
  38.         }  
  39.     }  
  40. private:  
  41.     T* _p;  
  42. };  
  43. void Funtest()  
  44. {  
  45.     AutoPtr<int> p = new int;  
  46.     AutoPtr<int> p1(p);  
  47.     AutoPtr<int> p2;  
  48.     p2 = p1;  
  49. }  
  50. int main()  
  51. {  
  52.     Funtest();  
  53.     system("pause");  
  54.     return 0;  
  55. }  


运行过程截图:



运行结果:



(5)获取原生指针,重载*和->

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. template <typename T>  
  2. class AutoPtr  
  3. {  
  4. public:  
  5.     AutoPtr(T* ap = NULL)  
  6.         :_p(ap)  
  7.     {  
  8.         cout<<"AutoPtr()"<<endl;  
  9.     }  
  10.   
  11.     AutoPtr(AutoPtr<T>& ap)//由于内部要改变ap的值,所以去掉const修饰  
  12.         :_p(ap._p)  
  13.     {  
  14.         ap._p = NULL;//让ap与动态申请的空间脱离关系  
  15.     }  
  16.   
  17.     AutoPtr<T>& operator=(AutoPtr<T>& ap)  
  18.     {  
  19.         if(this != &ap)  
  20.         {  
  21.             if(NULL != _p)//防止对空对象进行引用导致程序崩溃  
  22.             {  
  23.                 delete _p;  
  24.                 _p = ap._p;//如果_p为空,则崩溃  
  25.                 ap._p = NULL;//脱离关系  
  26.             }  
  27.         }  
  28.         return *this;  
  29.     }  
  30.   
  31.     ~AutoPtr()  
  32.     {  
  33.         if(NULL != _p)  
  34.         {  
  35.             cout<<"~AutoPtr()"<<endl;  
  36.             delete _p;  
  37.             _p = NULL;  
  38.         }  
  39.     }  
  40.     T* Get()  
  41.     {  
  42.         return _p;  
  43.     }  
  44.     T* operator*()  
  45.     {  
  46.         return *_p;  
  47.     }  
  48.     T* operator->()  
  49.     {  
  50.         return _p;  
  51.     }  
  52. private:  
  53.     T* _p;  
  54. };  
  55. void Funtest()  
  56. {  
  57.     AutoPtr<int> p = new int;  
  58.     AutoPtr<int> p1(p);  
  59.     AutoPtr<int> p2;  
  60.     p2 = p1;  
  61.     AutoPtr<int>* p3 = &p1;  
  62.     cout<<*(p3->Get)()<<endl;  
  63. }  
  64. int main()  
  65. {  
  66.     Funtest();  
  67.     system("pause");  
  68.     return 0;  
  69. }  


运行过程截图: 


运行结果: 



auto_ptr致命缺陷:只能由一个对象管理所开辟的空间


2、老库中维护一个布尔变量owner实现---->owner_ptr


实现原理:构造对象时,将该对象的_owner赋值为TRUE,析构对象时,只有当该对象的_owner值为TRUE才释放,否则不释放

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. template <typename T>  
  2. class AutoPtr  
  3. {  
  4. public:  
  5.     AutoPtr(T* ap = NULL)  
  6.         :_p(ap)  
  7.         ,_owner(true)//说明这块空间已有对象占用  
  8.     {  
  9.         cout<<"AutoPtr()"<<endl;  
  10.     }  
  11.   
  12.     AutoPtr(AutoPtr<T>& ap)//由于内部要改变ap的值,所以去掉const修饰  
  13.         :_p(ap._p)  
  14.         ,_owner(true)  
  15.     {  
  16.         ap._owner = false;//让ap与动态申请的空间脱离关系  
  17.     }  
  18.   
  19.     AutoPtr<T>& operator=(AutoPtr<T>& ap)  
  20.     {  
  21.         if(this != &ap)  
  22.         {  
  23.             if(NULL != _p)//防止对空对象进行引用导致程序崩溃  
  24.             {  
  25.                 delete _p;  
  26.                 _p = ap._p;//如果_p为空,则崩溃  
  27.                 _owner = true;  
  28.                 ap._owner = false;//资源转移  
  29.             }  
  30.         }  
  31.         return *this;  
  32.     }  
  33.   
  34.     ~AutoPtr()  
  35.     {  
  36.         if(_owner &&NULL != _p)  
  37.         {  
  38.             cout<<"~AutoPtr()"<<endl;  
  39.             delete _p;  
  40.             _p = NULL;  
  41.             _owner = false;//释放完后将_owner赋值为false  
  42.         }  
  43.     }  
  44.     T* Get()  
  45.     {  
  46.         return _p;  
  47.     }  
  48.     T* operator*()  
  49.     {  
  50.         return *_p;  
  51.     }  
  52.     T* operator->()  
  53.     {  
  54.         return _p;  
  55.     }  
  56. private:  
  57.     T* _p;  
  58.     bool _owner;  
  59. };  
  60. void Funtest()  
  61. {  
  62.     AutoPtr<int> p = new int;  
  63.     AutoPtr<int> p1(p);  
  64.     AutoPtr<int> p2;  
  65.     p2 = p1;  
  66.     AutoPtr<int>* p3 = &p1;  
  67.     cout<<*(p3->Get)()<<endl;  
  68. }  
  69. int main()  
  70. {  
  71.     Funtest();  
  72.     system("pause");  
  73.     return 0;  
  74. }  

运行结果:



不足之处:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. template <typename T>  
  2. class AutoPtr  
  3. {  
  4. public:  
  5.     AutoPtr(T* ap = NULL)  
  6.         :_p(ap)  
  7.         ,_owner(true)//说明这块空间已有对象占用  
  8.     {  
  9.         cout<<"AutoPtr()"<<endl;  
  10.     }  
  11.   
  12.     AutoPtr(AutoPtr<T>& ap)//由于内部要改变ap的值,所以去掉const修饰  
  13.         :_p(ap._p)  
  14.         ,_owner(true)  
  15.     {  
  16.         ap._owner = false;//让ap与动态申请的空间脱离关系  
  17.     }  
  18.   
  19.     AutoPtr<T>& operator=(AutoPtr<T>& ap)  
  20.     {  
  21.         if(this != &ap)  
  22.         {  
  23.             if(NULL != _p)//防止对空对象进行引用导致程序崩溃  
  24.             {  
  25.                 delete _p;  
  26.                 _p = ap._p;//如果_p为空,则崩溃  
  27.                 _owner = true;  
  28.                 ap._owner = false;//资源转移  
  29.             }  
  30.         }  
  31.         return *this;  
  32.     }  
  33.   
  34.     ~AutoPtr()  
  35.     {  
  36.         if(_owner &&NULL != _p)  
  37.         {  
  38.             cout<<"~AutoPtr()"<<endl;  
  39.             delete _p;  
  40.             _p = NULL;  
  41.             _owner = false;//释放完后将_owner赋值为false  
  42.         }  
  43.     }  
  44.     T* Get()  
  45.     {  
  46.         return _p;  
  47.     }  
  48.     T* operator*()  
  49.     {  
  50.         return *_p;  
  51.     }  
  52.     T* operator->()  
  53.     {  
  54.         return _p;  
  55.     }  
  56. private:  
  57.     T* _p;  
  58.     bool _owner;  
  59. };  
  60. void Funtest()  
  61. {  
  62.     AutoPtr<int> sp1;  
  63.     if(true)  
  64.     {  
  65.         AutoPtr<int> sp2(sp1);  
  66.     }<span style="color:#33ff33;">//出了作用域sp1就成为野指针</span>  
  67.     AutoPtr<int> sp3;  
  68.     sp3 = sp1;  
  69. }  
  70. int main()  
  71. {  
  72.     Funtest();  
  73.     system("pause");  
  74.     return 0;  
  75. }  


运行过程截图:


运行结果:




总结:以上两种方式我们都是通过资源转移来防止一块空间被释放多次,auto_ptr的缺点是申请的空间最终只能由一个对象来管理,而owner_ptr虽然可通过多个对象管理空间,但却可能导致野指针等问题,这并不是我们的初衷,那么有什么更好的实现方法呢?


 

3、单个对象独占空间---->scoped_ptr 


(1)首先思考一个问题,一个类如何防止被拷贝疑问疑问疑问

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. class B  
  2. {  
  3. public:  
  4.     B()  
  5.     {  
  6.         cout<<"B()"<<endl;  
  7.     }  
  8. private:  
  9.     B(const B& b);  
  10.     B& operator=(const B& b);  
  11.   
  12. private:  
  13.     int _b;  
  14. };  
  15. void Funtest()  
  16. {  
  17.     B b1;  
  18.     B b2(b1);  
  19.     b2 = b1;  
  20. }  


编译结果:



所以说,一个类要防止被拷贝,要做两件工作

1>将拷贝构造函数和赋值运算符重载的访问权限设成私有的。

2>将拷贝构造函数和赋值运算符重载只给出声明而不对其进行定义。


(2)仿照上述思想,scopted_ptr的实现思想就是让单个对象独占空间,从而避免对象被多次释放的问题

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. template <typename T>  
  2. class AutoPtr  
  3. {  
  4. public:  
  5.     AutoPtr(T* ap = NULL)  
  6.         :_p(ap)  
  7.     {  
  8.         cout<<"AutoPtr()"<<endl;  
  9.     }  
  10.   
  11.     ~AutoPtr()  
  12.     {  
  13.         if(NULL != _p)  
  14.         {  
  15.             cout<<"~AutoPtr()"<<endl;  
  16.             delete _p;  
  17.             _p = NULL;  
  18.         }  
  19.     }  
  20.     T* Get()  
  21.     {  
  22.         return _p;  
  23.     }  
  24.     T* operator*()  
  25.     {  
  26.         return *_p;  
  27.     }  
  28.     T* operator->()  
  29.     {  
  30.         return _p;  
  31.     }  
  32. private:  
  33.     AutoPtr(const AutoPtr<T>& ap);  
  34.     AutoPtr<T>& operator=(const AutoPtr<T>& ap);  
  35. private:  
  36.     T* _p;  
  37. };  
  38. void Funtest()  
  39. {  
  40.     AutoPtr<int> p1 = new int;  
  41.     AutoPtr<int>* p2 = &p1;  
  42.     cout<<*(p2->Get)()<<endl;  
  43. }  
  44. int main()  
  45. {  
  46.     Funtest();  
  47.     system("pause");  
  48.     return 0;  
  49. }  


运行结果:



注意:应避免使用出错,不要进行对象拷贝和赋值


4、unique_ptr(即scopted_array)

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. template <typename T>  
  2. class AutoPtr  
  3. {  
  4. public:  
  5.     AutoPtr(T* ap = NULL)  
  6.         :_p(ap)  
  7.     {  
  8.         cout<<"AutoPtr()"<<endl;  
  9.     }  
  10.   
  11.     ~AutoPtr()  
  12.     {  
  13.         if(NULL != _p)  
  14.         {  
  15.             cout<<"~AutoPtr()"<<endl;  
  16.             delete _p;  
  17.             _p = NULL;  
  18.         }  
  19.     }  
  20.     T& operator[](size_t index)  
  21.     {  
  22.         return _p[index];  
  23.     }  
  24.     const T& operator[](size_t index)const  
  25.     {  
  26.         return _p[index];  
  27.     }  
  28.     T* Get()  
  29.     {  
  30.         return _p;  
  31.     }  
  32. private:  
  33.     AutoPtr(const AutoPtr<T>& ap);  
  34.     AutoPtr<T>& operator=(const AutoPtr<T>& ap);  
  35. private:  
  36.     T* _p;  
  37. };  
  38. void Funtest()  
  39. {  
  40.     AutoPtr<int> p(new int[5]);   
  41.     p[0] = 1;  
  42.     p[1] = 2;  
  43.     p[2] = 3;  
  44.     p[3] = 4;  
  45.     p[4] = 5;  
  46.     for(size_t i=0; i<5; i++)  
  47.     {  
  48.         cout<<p[i]<<" ";  
  49.     }  
  50. }  
  51. int main()  
  52. {  
  53.     Funtest();  
  54.     system("pause");  
  55.     return 0;  
  56. }  

运行结果:


注意:unique_ptr在boost库中是没有的,因为它就好比一个动态开辟的数组,可以用vector来实现,接口多,用着还方便,故有点多余。


5、引用计数版本的智能指针---->shared_ptr

     前面在string类中我们介绍过引用计数版本的各种情况分析,在这里我们就不啰嗦了,直接给出指针版本的。


有兴趣了解的请看:string类详解:

 http://blog.csdn.net/snow_5288/article/details/52901528




赋值运算符重载情况分类:


[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. template <typename T>//引用计数版本  
  2. class SharedPtr  
  3. {  
  4. public:  
  5.     SharedPtr(T* sp = NULL)  
  6.         :_p(sp)  
  7.         ,_pCount(NULL)  
  8.     {  
  9.         cout<<"SharedPtr()"<<endl;  
  10.         if(NULL != _p)  
  11.         {  
  12.             _pCount = new int(1);//仅当对象不为空时,才为其引用计数赋值  
  13.         }  
  14.     }  
  15.       
  16.     SharedPtr(SharedPtr<T>& sp)//由于内部要改变ap的值,所以去掉const修饰  
  17.         :_p(sp._p)  
  18.         ,_pCount(sp._pCount)  
  19.     {  
  20.         if(NULL != _p)//防止拷贝的对象本就是空  
  21.             ++(*_pCount);  
  22.         sp._p = NULL;//让ap与动态申请的空间脱离关系  
  23.     }  
  24.       
  25.     SharedPtr<T>& operator=(SharedPtr<T>& sp)  
  26.     {  
  27.         if(this != &sp)//  
  28.         {  
  29.             if(NULL == _pCount)//当前对象没有管理空间  
  30.             {  
  31.                 _p = sp._p;  
  32.                 _pCount = sp._pCount;  
  33.                 if(sp._pCount)//原有空间管理了一段空间  
  34.                     ++(*_pCount);  
  35.             }  
  36.             else if(_pCount && 1==(*_pCount))//当前对象独占一块空间  
  37.             {  
  38.                 delete _p;//释放当前对象  
  39.                 delete _pCount;//释放当前对象  
  40.                   
  41.                 _p = sp._p;  
  42.                 _pCount = sp._pCount;  
  43.                 if(sp._pCount)//原有空间管理了一段空间  
  44.                     ++(*_pCount);  
  45.             }  
  46.             else//当前对象和别人共享一段空间  
  47.             {  
  48.                 --(*_pCount);  
  49.                   
  50.                 _p = sp._p;  
  51.                 _pCount = sp._pCount;  
  52.                 if(sp._pCount)//原有空间管理了一段空间  
  53.                     ++(*_pCount);  
  54.             }  
  55.         }  
  56.         return *this;  
  57.     }  
  58.       
  59.     ~SharedPtr()  
  60.     {  
  61.         if(_pCount && 0==(--(*_pCount)))//注意释放条件  
  62.         {  
  63.             cout<<"~SharedPtr()"<<endl;  
  64.             delete _p;  
  65.             delete _pCount;//一定不要忘了释放  
  66.             _p = NULL;  
  67.             _pCount = NULL;  
  68.         }  
  69.     }  
  70.     T* operator*()  
  71.     {  
  72.         return *_p;  
  73.     }  
  74.     T* operator->()  
  75.     {  
  76.         return _p;  
  77.     }  
  78. private:  
  79.     T* _p;  
  80.     int* _pCount;  
  81. };  
  82.   
  83. void FunTest()  
  84. {  
  85.     SharedPtr<int> sp1(NULL);  
  86.     SharedPtr<int> sp2(new int);  
  87.     SharedPtr<int> sp3(sp2);//sp2、sp3共享空间  
  88.     SharedPtr<int> sp4 = new int;//sp4独占空间  
  89.     SharedPtr<int> sp5(new int);  
  90.     sp4 = sp2;//当前对象独占空间  
  91.     sp1 = sp4;//当前对象sp1没有管理空间  
  92.     sp2 = sp5;  
  93. }  
  94. int main()  
  95. {  
  96.     FunTest();  
  97.     system("pause");  
  98.     return 0;  
  99. }  

运行过程:


运行结果:

结论:shared_ptr可通过多个对象对申请的空间进行访问。

6>定置删除器(仿函数实现)
    
    上述5种实现智能指针的通病:由于文件指针用fopen打开之后必须拿对应的fclose函数将其关闭,故它们处理不了文件指针,所以就必须引出仿函数。

仿函数(functor):STL的六大组件之一,也叫函数对象。就是使一个类的使用看上去像一个函数。其实现原理就是就是在类中重载(),这个类就有了类似函数的行为,同时也成为一个仿函数类了。

用函数实现文件指针的关闭
[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #include<iostream>  
  2. #include<memory>  
  3. using namespace std;  
  4.   
  5. void Fclose(FILE* pf)  
  6. {  
  7.     if(pf)  
  8.         fclose(pf);  
  9. }  
  10. int main()  
  11. {  
  12.     FILE* pf = fopen("1.txt","r");  
  13.     shared_ptr<FILE> sp(pf,Fclose);  
  14.     system("pause");  
  15.     return 0;  
  16. }  

用仿函数实现
[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #include<iostream>  
  2. #include<memory>  
  3. using namespace std;  
  4.   
  5. class Fclose// 定置的删除器仿函数  
  6. {  
  7. public:  
  8.     void operator()(FILE* pf)  
  9.     {  
  10.         if(NULL != pf)  
  11.             fclose(pf);  
  12.     }  
  13. };  
  14.   
  15. int main()  
  16. {  
  17.     FILE* pf = fopen("1.txt","r");  
  18.     shared_ptr<FILE> sp(pf,Fclose());  
  19.     system("pause");  
  20.     return 0;  
  21. }  

7>智能指针应用举例:实现多重冒泡排序
[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <pre code_snippet_id="2008345" snippet_file_name="blog_20161125_17_3228611" name="code" class="cpp">template <typename T>  
  2. class Great//按照升序冒泡  
  3. {  
  4. public:  
  5.     bool operator()(T& left,T& right)  
  6.     {  
  7.         return left>right;  
  8.     }  
  9. };  
  10. template <typename T>  
  11. class Less//按照降序冒泡  
  12. {  
  13. public:  
  14.     bool operator()(T& left,T& right)  
  15.     {  
  16.         return left<right;  
  17.     }  
  18. };  
  19. template <typename T,typename Compare>  
  20. void BubbleSort(T arr[],size_t size)  
  21. {  
  22.     size_t i,j;  
  23.     int flag = 0;  
  24.     for(i = 0; i<size-1; i++)  
  25.     {  
  26.         flag = 0;  
  27.         for(j = 0; j<size-1-i; j++)  
  28.         {  
  29.             if(Compare()(arr[j],arr[j+1]))//注意传参  
  30.             {  
  31.                 flag = 1;  
  32.                 swap(arr[j],arr[j+1]);  
  33.             }  
  34.         }  
  35.         if(flag == 0)  
  36.             break;  
  37.     }  
  38. }  
  39.   
  40. int main()  
  41. {  
  42.     int arr[10] = {9,5,3,4,7,2,1,8,6,0};  
  43.     size_t size = sizeof(arr)/sizeof(arr[0]);  
  44.     BubbleSort<int,Less<int>>(arr,size);  
  45.     size_t idx = 0;  
  46.     cout<<"降序"<<endl;  
  47.     for(idx=0; idx<size; idx++)  
  48.     {  
  49.         cout<<arr[idx]<<" ";  
  50.     }  
  51.     cout<<endl<<endl;  
  52.     BubbleSort<int,Great<int>>(arr,size);  
  53.     cout<<"升序"<<endl;  
  54.     for(idx=0; idx<size; idx++)  
  55.     {  
  56.         cout<<arr[idx]<<" ";  
  57.     }  
  58.     system("pause");  
  59.     return 0;  
  60. }</pre><br>  
  61. <br>  
  62. <pre></pre>  
  63. 运行结果:  
  64. <pre></pre>  



8>智能指针<专指shared_ptr>的循环引用(非常重要)

先看一下什么是循环引用问题:

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #include <iostream>  
  2. #include <memory>  
  3. using namespace std;  
  4.   
  5. template <typename T>  
  6. class Node  
  7. {  
  8. public:  
  9.     Node(const T& value)  
  10.         :_pPre(NULL)  
  11.         ,_pNext(NULL)  
  12.         ,_value(value)  
  13.     {  
  14.         cout<<"Node()"<<endl;  
  15.     }  
  16.     ~Node()  
  17.     {  
  18.         cout<<"~Node()"<<endl;  
  19.         cout<<"this:"<<this<<endl;  
  20.     }  
  21.   
  22.     shared_ptr<Node<T>> _pPre;  
  23.     shared_ptr<Node<T>> _pNext;  
  24.     T _value;  
  25. };  
  26. void Funtest()  
  27. {  
  28.     shared_ptr<Node<int>> sp1(new Node<int>(1));  
  29.     shared_ptr<Node<int>> sp2(new Node<int>(2));  
  30.   
  31.     cout<<"sp1.use_count:"<<sp1.use_count()<<endl;  
  32.     cout<<"sp2.use_count:"<<sp2.use_count()<<endl;  
  33.   
  34.     sp1->_pNext = sp2;  
  35.     sp2->_pPre = sp1;  
  36.   
  37.     cout<<"sp1.use_count:"<<sp1.use_count()<<endl;  
  38.     cout<<"sp2.use_count:"<<sp2.use_count()<<endl;  
  39. }  
  40. int main()  
  41. {  
  42.     Funtest();  
  43.     system("pause");  
  44.     return 0;  
  45. }  
运行结果:



从运行结果中我们可以清楚地看到程序运行完成之后并没有释放我们的对象sp1和sp2,那么这是什么原因造成的呢?


从上面shared_ptr的实现中我们知道了只有当引用计数减减之后等于0,析构时才会释放对象,而上述情况造成了一个僵局,那就是析构对象时先析构sp2,可是由于sp2的空间sp1还在使用中,所以sp2.use_count减减之后为1,不释放,sp1也是相同的道理,由于sp1的空间sp2还在使用中,所以sp1.use_count减减之后为1,也不释放。sp1等着sp2先释放,sp2等着sp1先释放,二者互不相让,导致最终都没能释放,内存泄漏


解决办法:使用弱指针---->weak_ptr

[cpp]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #include <iostream>  
  2. #include <memory>  
  3. using namespace std;  
  4.   
  5. template <typename T>  
  6. struct Node  
  7. {  
  8. public:  
  9.     Node(const T& value)  
  10.         :_value(value)  
  11.     {  
  12.         cout<<"Node()"<<endl;  
  13.     }  
  14.     ~Node()  
  15.     {  
  16.         cout<<"~Node()"<<endl;  
  17.         cout<<"this:"<<this<<endl;  
  18.     }  
  19.   
  20.     <span style="color:#ff0000;">weak_ptr<Node<T>> _pPre;  
  21.     weak_ptr<Node<T>> _pNext;</span>  
  22.     T _value;  
  23. };  
  24. void Funtest()  
  25. {  
  26.     shared_ptr<Node<int>> sp1(new Node<int>(1));  
  27.     shared_ptr<Node<int>> sp2(new Node<int>(2));  
  28.   
  29.     cout<<"sp1.use_count:"<<sp1.use_count()<<endl;  
  30.     cout<<"sp2.use_count:"<<sp2.use_count()<<endl;  
  31.       
  32.     sp1->_pNext = sp2;  
  33.     sp2->_pPre = sp1;  
  34.   
  35.     cout<<"sp1.use_count:"<<sp1.use_count()<<endl;  
  36.     cout<<"sp2.use_count:"<<sp2.use_count()<<endl;  
  37. }  
  38. int main()  
  39. {  
  40.     Funtest();  
  41.     system("pause");  
  42.     return 0;  
  43. }  
运行结果:


分析过程:


析构对象时,先析构sp2,可是由于sp2.use_count减减之后为0,释放sp2,sp1.use_count减减之后为0,释放sp1.

小细节:由于我们的引用计数也是智能指针,维护了一块空间,当第一次调用完析构函数时,sp2.weak_count--==1未能释放,此时sp1.weak_count也减减等于1,下一次调用析构函数时,sp1.weak_count--==0释放。


boost/shared_ptr的框架uml类图



 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值