当前位置:   article > 正文

【C++航海王:追寻罗杰的编程之路】智能指针

【C++航海王:追寻罗杰的编程之路】智能指针

目录

1 -> 为什么需要智能指针?

2 -> 内存泄漏

2.1 ->什么是内存泄漏,以及内存泄漏的危害

2.2 -> 内存泄漏分类

2.3 -> 如何避免内存泄漏

3 -> 智能指针的使用及原理

3.1 -> RAII

3.2 -> 智能指针的原理

3.3 -> std::auto_ptr

3.4 -> std::unique_ptr

3.5 -> std::shared_ptr

4 -> C++11和boost中智能指针的关系


1 -> 为什么需要智能指针

先分析下面这段程序有没有什么内存方面的问题?

  1. #define _CRT_SECURE_NO_WARNINGS 1
  2. #include <iostream>
  3. using namespace std;
  4. int div()
  5. {
  6. int a, b;
  7. cin >> a >> b;
  8. if (b == 0)
  9. throw invalid_argument("除0错误");
  10. return a / b;
  11. }
  12. void Func()
  13. {
  14. // 1、如果p1这里new 抛异常会如何?
  15. // 2、如果p2这里new 抛异常会如何?
  16. // 3、如果div调用这里又会抛异常会如何?
  17. int* p1 = new int;
  18. int* p2 = new int;
  19. cout << div() << endl;
  20. delete p1;
  21. delete p2;
  22. }
  23. int main()
  24. {
  25. try
  26. {
  27. Func();
  28. }
  29. catch (exception& e)
  30. {
  31. cout << e.what() << endl;
  32. }
  33. return 0;
  34. }

2 -> 内存泄漏

2.1 ->什么是内存泄漏,以及内存泄漏的危害

什么是内存泄漏:内存泄漏是指因为疏忽或者错误造成程序未能释放已经不再使用的内存的情况。内存泄漏并不是指内存在物理上的消失,而是应用程序分配某段内存后,因为设计错误,失去了对该段内存的控制,因而造成了内存的浪费。

内存泄漏的危害:长期运行的程序出现内存泄漏,影响很大,如操作系统、后台服务等等,出现内存泄漏会导致响应越来越慢,最终卡死。

  1. void MemoryLeaks()
  2. {
  3. // 1.内存申请了忘记释放
  4. int* p1 = (int*)malloc(sizeof(int));
  5. int* p2 = new int;
  6. // 2.异常安全问题
  7. int* p3 = new int[10];
  8. Func(); // 这里Func函数抛异常导致 delete[] p3未执行,p3没被释放.
  9. delete[] p3;
  10. }

2.2 -> 内存泄漏分类

C/C++程序中一般关心两种方面的内存泄漏:

  • 堆内存泄漏(Heap Leak)

堆内存指的是程序执行中依据须要分配通过malloc/calloc/realloc/new等从堆中分配的一块内存,用完后必须通过调用相应的free或者delete删掉。假设程序的设计错误导致这部分内存没有被释放,那么以后这部分空间将无法再次被使用,就会产生Heap Leak。

  • 系统资源泄漏

指程序使用系统分配的资源,比如套接字、文件描述符、管道等没有使用对应的函数释放掉,导致系统资源的浪费,严重可导致系统效能减少,系统执行不稳定。 

2.3 -> 如何避免内存泄漏

  1. 工程前期良好的设计规范,养成良好的编码规范,申请的内存空间记得释放。ps:这个是理想状态。但是如果碰上异常时,就算注意释放了,还是可能会出问题。需要下一条智能指针来管理才有保证。
  2. 采用RAII思想或者智能指针来管理资源。
  3. 有些公司内部规范使用内部实现的私有内存管理库。这套库自带内存泄漏检测的功能选项。
  4. 出问题了使用内存泄漏工具检测。ps:不过很多工具都不靠谱,或者收费昂贵。

总结:

内存泄漏非常常见,解决方案分为两种:

  1. 事前预防型。如智能指针等;
  2. 事后查错型。如泄漏检测工具。

3 -> 智能指针的使用及原理

3.1 -> RAII

RAII(Resource Acquisition Is Initialization)是一种利用对象生命周期来控制程序资源(如内存、文件句柄、网络连接、互斥量等等)的简单技术。

在对象构造时获取资源,接着控制对资源的访问使之在对象的生命周期内始终保持有效,最后在对象析构的时候释放资源。借此,实际上把管理一份资源的责任托管给了一个对象。这种做法有两大好处:

  • 不需要显式地释放资源。
  • 采用这种方式,对象所需的资源在其生命周期内始终保持有效。
  1. // 使用RAII思想设计的SmartPtr类
  2. template<class T>
  3. class SmartPtr {
  4. public:
  5. SmartPtr(T* ptr = nullptr)
  6. : _ptr(ptr)
  7. {}
  8. ~SmartPtr()
  9. {
  10. if (_ptr)
  11. delete _ptr;
  12. }
  13. private:
  14. T* _ptr;
  15. };
  16. int div()
  17. {
  18. int a, b;
  19. cin >> a >> b;
  20. if (b == 0)
  21. throw invalid_argument("除0错误");
  22. return a / b;
  23. }
  24. void Func()
  25. {
  26. SmartPtr<int> sp1(new int);
  27. SmartPtr<int> sp2(new int);
  28. cout << div() << endl;
  29. }
  30. int main()
  31. {
  32. try
  33. {
  34. Func();
  35. }
  36. catch (const exception& e)
  37. {
  38. cout << e.what() << endl;
  39. }
  40. return 0;
  41. }

3.2 -> 智能指针的原理

上述的SmartPtr还不能将其称为智能指针,因为它还不具有指针的行为。指针可以解引用,也可以通过->去访问所指空间中的内容,因此:AutoPtr模板类中还需要将*、->重载下,才可以让其像指针一样去使用。

  1. template<class T>
  2. class SmartPtr {
  3. public:
  4. SmartPtr(T* ptr = nullptr)
  5. : _ptr(ptr)
  6. {}
  7. ~SmartPtr()
  8. {
  9. if (_ptr)
  10. delete _ptr;
  11. }
  12. T& operator*() { return *_ptr; }
  13. T* operator->() { return _ptr; }
  14. private:
  15. T* _ptr;
  16. };
  17. struct Date
  18. {
  19. int _year;
  20. int _month;
  21. int _day;
  22. };
  23. int main()
  24. {
  25. SmartPtr<int> sp1(new int);
  26. *sp1 = 10;
  27. cout << *sp1 << endl;
  28. SmartPtr<Date> sparray(new Date);
  29. // 需要注意的是这里应该是sparray.operator->()->_year = 2018;
  30. // 本来应该是sparray->->_year这里语法上为了可读性,省略了一个->
  31. sparray->_year = 2018;
  32. sparray->_month = 1;
  33. sparray->_day = 1;
  34. }

总结一下智能指针的原理:

  1. RAII特性
  2. 重载operator*和operator->,具有像指针一样的行为。

3.3 -> std::auto_ptr

 std::auto_ptr文档介绍

C++98版本的库中就提供了auto_ptr的智能指针。下面演示auto_ptr的使用及问题。

auto_ptr的实现原理:管理权转移的思想,下面简化模拟实现了一份fyd::auto_ptr来了解它的原理。  

  1. // C++98 管理权转移 auto_ptr
  2. namespace fyd
  3. {
  4. template<class T>
  5. class auto_ptr
  6. {
  7. public:
  8. auto_ptr(T* ptr)
  9. :_ptr(ptr)
  10. {}
  11. auto_ptr(auto_ptr<T>& sp)
  12. :_ptr(sp._ptr)
  13. {
  14. // 管理权转移
  15. sp._ptr = nullptr;
  16. }
  17. auto_ptr<T>& operator=(auto_ptr<T>& ap)
  18. {
  19. // 检测是否为自己给自己赋值
  20. if (this != &ap)
  21. {
  22. // 释放当前对象中资源
  23. if (_ptr)
  24. delete _ptr;
  25. // 转移ap中资源到当前对象中
  26. _ptr = ap._ptr;
  27. ap._ptr = NULL;
  28. }
  29. return *this;
  30. }
  31. ~auto_ptr()
  32. {
  33. if (_ptr)
  34. {
  35. cout << "delete:" << _ptr << endl;
  36. delete _ptr;
  37. }
  38. }
  39. // 像指针一样使用
  40. T& operator*()
  41. {
  42. return *_ptr;
  43. }
  44. T* operator->()
  45. {
  46. return _ptr;
  47. }
  48. private:
  49. T* _ptr;
  50. };
  51. }
  52. //int main()
  53. //{
  54. // std::auto_ptr<int> sp1(new int);
  55. // std::auto_ptr<int> sp2(sp1); // 管理权转移
  56. //
  57. // // sp1悬空
  58. // *sp2 = 10;
  59. // cout << *sp2 << endl;
  60. // cout << *sp1 << endl;
  61. //
  62. // return 0;
  63. //}

结论:auto_ptr是一个失败的设计,很多公司明确要求不能使用auto_ptr。

3.4 -> std::unique_ptr

std::unique_ptr文档介绍 

C++11中开始提供更靠谱的unique_ptr。

unique_ptr的实现原理:简单粗暴的防拷贝,下面简化实现了一份fyd::unique_ptr来了解它的原理。

  1. // C++11库才更新智能指针实现
  2. // C++11出来之前,boost搞除了更好用的scoped_ptr/shared_ptr/weak_ptr
  3. // C++11将boost库中智能指针精华部分吸收了过来
  4. // C++11->unique_ptr/shared_ptr/weak_ptr
  5. // unique_ptr/scoped_ptr
  6. // 原理:简单粗暴 -- 防拷贝
  7. namespace fyd
  8. {
  9. template<class T>
  10. class unique_ptr
  11. {
  12. public:
  13. unique_ptr(T* ptr)
  14. :_ptr(ptr)
  15. {}
  16. ~unique_ptr()
  17. {
  18. if (_ptr)
  19. {
  20. cout << "delete:" << _ptr << endl;
  21. delete _ptr;
  22. }
  23. }
  24. // 像指针一样使用
  25. T& operator*()
  26. {
  27. return *_ptr;
  28. }
  29. T* operator->()
  30. {
  31. return _ptr;
  32. }
  33. unique_ptr(const unique_ptr<T>&sp) = delete;
  34. unique_ptr<T>& operator=(const unique_ptr<T>&sp) = delete;
  35. private:
  36. T* _ptr;
  37. };
  38. }
  39. //int main()
  40. //{
  41. // fyd::unique_ptr<int> sp1(new int);
  42. // fyd::unique_ptr<int> sp2(sp1);
  43. //
  44. // std::unique_ptr<int> sp1(new int);
  45. // std::unique_ptr<int> sp2(sp1);
  46. //
  47. // return 0;
  48. //}

3.5 -> std::shared_ptr

std::shared_ptr文档介绍

C++11中开始提供更靠谱的并且支持拷贝的shared_ptr。

shared_ptr的原理:通过引用计数的方式来实现多个shared_ptr对象之间共享资源。

  1. shared_ptr在其内部,给每个资源都维护一份计数,用来记录该份资源被几个对象共享。
  2. 对象销毁时(也就是析构函数调用),就说明自己不使用该资源了,对象的引用计数减一。
  3. 如果引用计数是0,就说明自己是最后一个使用该资源的对象,必须释放该资源
  4. 如果不是0,就说明除了自己还有其他对象在使用该份资源,不能释放该资源,否则其他对象就成野指针了。
  1. // 引用计数支持多个拷贝管理同一个资源,最后一个析构对象释放资源
  2. namespace fyd
  3. {
  4. template<class T>
  5. class shared_ptr
  6. {
  7. public:
  8. shared_ptr(T* ptr = nullptr)
  9. :_ptr(ptr)
  10. , _pRefCount(new int(1))
  11. , _pmtx(new mutex)
  12. {}
  13. shared_ptr(const shared_ptr<T>& sp)
  14. :_ptr(sp._ptr)
  15. , _pRefCount(sp._pRefCount)
  16. , _pmtx(sp._pmtx)
  17. {
  18. AddRef();
  19. }
  20. void Release()
  21. {
  22. _pmtx->lock();
  23. bool flag = false;
  24. if (--(*_pRefCount) == 0 && _ptr)
  25. {
  26. cout << "delete:" << _ptr << endl;
  27. delete _ptr;
  28. delete _pRefCount;
  29. flag = true;
  30. }
  31. _pmtx->unlock();
  32. if (flag == true)
  33. {
  34. delete _pmtx;
  35. }
  36. }
  37. void AddRef()
  38. {
  39. _pmtx->lock();
  40. ++(*_pRefCount);
  41. _pmtx->unlock();
  42. }
  43. shared_ptr<T>& operator=(const shared_ptr<T>& sp)
  44. {
  45. //if (this != &sp)
  46. if (_ptr != sp._ptr)
  47. {
  48. Release();
  49. _ptr = sp._ptr;
  50. _pRefCount = sp._pRefCount;
  51. _pmtx = sp._pmtx;
  52. AddRef();
  53. }
  54. return *this;
  55. }
  56. int use_count()
  57. {
  58. return *_pRefCount;
  59. }
  60. ~shared_ptr()
  61. {
  62. Release();
  63. }
  64. // 像指针一样使用
  65. T& operator*()
  66. {
  67. return *_ptr;
  68. }
  69. T* operator->()
  70. {
  71. return _ptr;
  72. }
  73. T* get() const
  74. {
  75. return _ptr;
  76. }
  77. private:
  78. T* _ptr;
  79. int* _pRefCount;
  80. mutex* _pmtx;
  81. };
  82. // 简化版本的weak_ptr实现
  83. template<class T>
  84. class weak_ptr
  85. {
  86. public:
  87. weak_ptr()
  88. :_ptr(nullptr)
  89. {}
  90. weak_ptr(const shared_ptr<T>& sp)
  91. :_ptr(sp.get())
  92. {}
  93. weak_ptr<T>& operator=(const shared_ptr<T>& sp)
  94. {
  95. _ptr = sp.get();
  96. return *this;
  97. }
  98. T& operator*()
  99. {
  100. return *_ptr;
  101. }
  102. T* operator->()
  103. {
  104. return _ptr;
  105. }
  106. private:
  107. T* _ptr;
  108. };
  109. }
  110. // shared_ptr智能指针是线程安全的吗?
  111. // 是的,引用计数的加减是加锁保护的。但是指向资源不是线程安全的
  112. // 指向堆上资源的线程安全问题是访问的人处理的,智能指针不管,也管不了
  113. // 引用计数的线程安全问题,是智能指针要处理的
  114. //int main()
  115. //{
  116. // fyd::shared_ptr<int> sp1(new int);
  117. // fyd::shared_ptr<int> sp2(sp1);
  118. // fyd::shared_ptr<int> sp3(sp1);
  119. //
  120. // fyd::shared_ptr<int> sp4(new int);
  121. // fyd::shared_ptr<int> sp5(sp4);
  122. //
  123. // sp1 = sp1;
  124. // sp1 = sp2;
  125. //
  126. // sp1 = sp4;
  127. // sp2 = sp4;
  128. // sp3 = sp4;
  129. //
  130. // *sp1 = 2;
  131. // *sp2 = 3;
  132. //
  133. // return 0;
  134. //}

std::shared_ptr的线程安全问题

通过下面的程序可以测试shared_ptr的线程安全问题。需要注意的是shared_ptr的线程安全分为两个方面:

  1. 智能指针对象中引用计数是多个智能指针对象共享的,两个线程中智能指针的引用计数同时++或--,引用计数原来是1,++了两次,可能还是2。这样引用计数就错乱了。会导致资源未释放或者程序崩溃的问题。所以只能指针中引用计数++、--是需要加锁的,也就是说引用计数的操作是线程安全的。
  2. 智能指针管理的对象存放在堆上,两个线程中同时去访问,会导致线程安全问题。
  1. // 1.演示引用计数线程安全问题,就把AddRefCount和SubRefCount中的锁去掉
  2. // 2.演示可能不出现线程安全问题,因为线程安全问题是偶现性问题,main函数的n改大一些概率就变大了,就容易出现了。
  3. // 3.下面代码我们使用SharedPtr演示,是为了方便演示引用计数的线程安全问题,
  4. // 将代码中的SharedPtr换成shared_ptr进行测试,可以验证库的shared_ptr,发现结论是一样的。
  5. namespace fyd
  6. {
  7. template<class T>
  8. class shared_ptr
  9. {
  10. public:
  11. shared_ptr(T* ptr = nullptr)
  12. :_ptr(ptr)
  13. , _pRefCount(new int(1))
  14. , _pmtx(new mutex)
  15. {}
  16. shared_ptr(const shared_ptr<T>& sp)
  17. :_ptr(sp._ptr)
  18. , _pRefCount(sp._pRefCount)
  19. , _pmtx(sp._pmtx)
  20. {
  21. AddRef();
  22. }
  23. void Release()
  24. {
  25. _pmtx->lock();
  26. bool flag = false;
  27. if (--(*_pRefCount) == 0 && _ptr)
  28. {
  29. cout << "delete:" << _ptr << endl;
  30. delete _ptr;
  31. delete _pRefCount;
  32. flag = true;
  33. }
  34. _pmtx->unlock();
  35. if (flag == true)
  36. {
  37. delete _pmtx;
  38. }
  39. }
  40. void AddRef()
  41. {
  42. _pmtx->lock();
  43. ++(*_pRefCount);
  44. _pmtx->unlock();
  45. }
  46. shared_ptr<T>& operator=(const shared_ptr<T>& sp)
  47. {
  48. //if (this != &sp)
  49. if (_ptr != sp._ptr)
  50. {
  51. Release();
  52. _ptr = sp._ptr;
  53. _pRefCount = sp._pRefCount;
  54. _pmtx = sp._pmtx;
  55. AddRef();
  56. }
  57. return *this;
  58. }
  59. int use_count()
  60. {
  61. return *_pRefCount;
  62. }
  63. ~shared_ptr()
  64. {
  65. Release();
  66. }
  67. // 像指针一样使用
  68. T& operator*()
  69. {
  70. return *_ptr;
  71. }
  72. T* operator->()
  73. {
  74. return _ptr;
  75. }
  76. T* get() const
  77. {
  78. return _ptr;
  79. }
  80. private:
  81. T* _ptr;
  82. int* _pRefCount;
  83. mutex* _pmtx;
  84. };
  85. // 简化版本的weak_ptr实现
  86. template<class T>
  87. class weak_ptr
  88. {
  89. public:
  90. weak_ptr()
  91. :_ptr(nullptr)
  92. {}
  93. weak_ptr(const shared_ptr<T>& sp)
  94. :_ptr(sp.get())
  95. {}
  96. weak_ptr<T>& operator=(const shared_ptr<T>& sp)
  97. {
  98. _ptr = sp.get();
  99. return *this;
  100. }
  101. T& operator*()
  102. {
  103. return *_ptr;
  104. }
  105. T* operator->()
  106. {
  107. return _ptr;
  108. }
  109. private:
  110. T* _ptr;
  111. };
  112. }
  113. struct Date
  114. {
  115. int _year = 0;
  116. int _month = 0;
  117. int _day = 0;
  118. };
  119. void SharePtrFunc(fyd::shared_ptr<Date>& sp, size_t n, mutex& mtx)
  120. {
  121. cout << sp.get() << endl;
  122. for (size_t i = 0; i < n; ++i)
  123. {
  124. // 这里智能指针拷贝会++计数,智能指针析构会--计数,这里是线程安全的。
  125. fyd::shared_ptr<Date> copy(sp);
  126. // 这里智能指针访问管理的资源,不是线程安全的。
  127. // 所以我们看看这些值两个线程++2n次,但是最终看到的结果,并一定是加了2n
  128. {
  129. unique_lock<mutex> lk(mtx);
  130. copy->_year++;
  131. copy->_month++;
  132. copy->_day++;
  133. }
  134. }
  135. }
  136. int main()
  137. {
  138. fyd::shared_ptr<Date> p(new Date);
  139. cout << p.get() << endl;
  140. const size_t n = 100000;
  141. mutex mtx;
  142. thread t1(SharePtrFunc, std::ref(p), n, std::ref(mtx));
  143. thread t2(SharePtrFunc, std::ref(p), n, std::ref(mtx));
  144. t1.join();
  145. t2.join();
  146. cout << p->_year << endl;
  147. cout << p->_month << endl;
  148. cout << p->_day << endl;
  149. cout << p.use_count() << endl;
  150. return 0;
  151. }

std::shared_ptr的循环引用

  1. struct ListNode
  2. {
  3. int _data;
  4. shared_ptr<ListNode> _prev;
  5. shared_ptr<ListNode> _next;
  6. ~ListNode() { cout << "~ListNode()" << endl; }
  7. };
  8. int main()
  9. {
  10. shared_ptr<ListNode> node1(new ListNode);
  11. shared_ptr<ListNode> node2(new ListNode);
  12. cout << node1.use_count() << endl;
  13. cout << node2.use_count() << endl;
  14. node1->_next = node2;
  15. node2->_prev = node1;
  16. cout << node1.use_count() << endl;
  17. cout << node2.use_count() << endl;
  18. return 0;
  19. }

循环引用分析:

  1. node1和node2两个智能指针对象指向两个节点,引用计数变成1,我们不需要手动delete。
  2. node1的_next指向node2,node2的_prev指向node1,引用计数变成2。
  3. node1和node2析构,引用计数减到1,但是_next还指向下一个节点,_prev还指向上一个节点。
  4. 也就是说_next析构了,node2就释放了。
  5. 也就是说_prev析构了,node1就释放了。
  6. 但是_next属于node的成员,node1释放了,_next才会析构,而node1由_prev管理,_prev属于node2成员,所以这就叫循环引用,谁也不释放。

  1. // 解决方案:在引用计数的场景下,把节点中的_prev和_next改成weak_ptr就可以了
  2. // 原理就是,node1->_next = node2;和node2->_prev = node1;时
  3. // weak_ptr的_next和_prev不会增加node1和node2的引用计数。
  4. struct ListNode
  5. {
  6. int _data;
  7. weak_ptr<ListNode> _prev;
  8. weak_ptr<ListNode> _next;
  9. ~ListNode() { cout << "~ListNode()" << endl; }
  10. };
  11. int main()
  12. {
  13. shared_ptr<ListNode> node1(new ListNode);
  14. shared_ptr<ListNode> node2(new ListNode);
  15. cout << node1.use_count() << endl;
  16. cout << node2.use_count() << endl;
  17. node1->_next = node2;
  18. node2->_prev = node1;
  19. cout << node1.use_count() << endl;
  20. cout << node2.use_count() << endl;
  21. return 0;
  22. }

如果不是new出来的对象如何通过智能指针管理呢?其实shared_ptr设计了一个删除器来解决这个问题。

  1. // 仿函数的删除器
  2. template<class T>
  3. struct FreeFunc {
  4. void operator()(T* ptr)
  5. {
  6. cout << "free:" << ptr << endl;
  7. free(ptr);
  8. }
  9. };
  10. template<class T>
  11. struct DeleteArrayFunc {
  12. void operator()(T* ptr)
  13. {
  14. cout << "delete[]" << ptr << endl;
  15. delete[] ptr;
  16. }
  17. };
  18. int main()
  19. {
  20. FreeFunc<int> freeFunc;
  21. std::shared_ptr<int> sp1((int*)malloc(4), freeFunc);
  22. DeleteArrayFunc<int> deleteArrayFunc;
  23. std::shared_ptr<int> sp2((int*)malloc(4), deleteArrayFunc);
  24. std::shared_ptr<int> sp4(new int[10], [](int* p) {delete[] p; });
  25. std::shared_ptr<FILE> sp5(fopen("test.txt", "w"), [](FILE* p)
  26. {fclose(p); });
  27. return 0;
  28. }

4 -> C++11和boost中智能指针的关系

  1. C++ 98中产生了第一个智能指针auto_ptr。
  2. C++ boost给出了更实用的scoped_ptr和shared_ptr和weak_ptr。
  3. C++ TR1,引入了shared_ptr等。不过值得注意的是TR1并不是标准版。
  4. C++11,引入了unique_ptr、shared_ptr和weak_ptr。需要注意的是unique_ptr对应boost的scoped_ptr。并且这些智能指针的实现原理是参考boost中的实现的。

感谢各位大佬支持!!!

互三啦!!!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/937061?site=
推荐阅读
相关标签
  

闽ICP备14008679号