当前位置:   article > 正文

C++进阶 —— 智能指针_c++ 智能指针

c++ 智能指针

目录

一,内存泄露

二,智能指针

智能指针的原理

三,C++库中的智能指针

auto_ptr

unique _ptr

shared_ptr

weak_ptr

附:RAII扩展        


一,内存泄露

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

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

内存泄露的分类

  • 堆内存泄露Heap Leak,指程序执行中通过malloc/calloc/realloc/new等从堆中分配的一块内存,用完后必须通过相应的free或delete释放掉;如这部分内存没有释放,就会造成这部分空间无法再被使用;
  • 系统资源泄露,指程序使用系统分配的资源,如套接字、文件描述符、管道等没有使用对应的函数释放掉,导致系统资源的浪费,严重可导致系统效能不稳定、系统执行不稳定;

避免内存泄露方式

  • 前期良好的设计规范,编码规范,申请的内存空间记着匹配释放;如碰上异常时,就算注意释放,也有可能出问题,需要智能指针来管理才有保证;采用RAII思想或智能指针来管理资源;
  • 公司内部规范,使用内部实现的私有内部管理库,这套库自带内存泄露检测的功能选项;出问题了使用内存泄露工具检测;
  • 内存泄露非常常见,有事前预防型(如智能指针等),事后查错型(如检测工具);

二,智能指针

        RAII(Resource Acquisition Is Initialization),是一种利用对象生命周期来控制程序资源的申请和释放;在对象构造时获取资源,控制对资源的访问使之在对象生命周期内始终保持有效,最后在对象析构的时候释放资源;借此,实际上把管理资源的责任托管给了一个对象;

        智能指针,是使用RAII技术的一种封装指针的类对象,重载了相应的运算符,可像指针一样运算,但会自动回收堆上的内存空间,从而避免内存泄露;

好处:

  • 不需要显式地释放资源;
  • 对象所需资源在其生命周期内始终有效;
  1. //RAII技术
  2. template<class T>
  3. class SmartPtr
  4. {
  5. public:
  6. SmartPtr(T* ptr = nullptr)
  7. :_ptr(ptr)
  8. {}
  9. ~SmartPtr()
  10. {
  11. if (_ptr)
  12. delete _ptr;
  13. }
  14. private:
  15. T* _ptr;
  16. };
  17. void Func(int* a, int n)
  18. {
  19. int* tmp = (int*)malloc(sizeof(int) * n);
  20. SmartPtr<int> sp(tmp);
  21. }
  22. int main()
  23. {
  24. try
  25. {
  26. int arr[] = { 1,2,3,4,5 };
  27. Func(arr, 5);
  28. }
  29. catch (const exception& e)
  30. {
  31. cout << e.what() << endl;
  32. }
  33. return 0;
  34. }

智能指针的原理

        上述SmartPtr还不能将其称为智能指针,因为其不具有指针行为;指针还可解引用及访问所指空间,因此AutoPtr模板类中还需有*、->重载,才可以让其像指针一样去使用;

  1. //智能指针类似指针,当还可自动回收内存
  2. template<class T>
  3. class SmartPtr
  4. {
  5. public:
  6. SmartPtr(T* ptr = nullptr)
  7. :_ptr(ptr)
  8. {}
  9. ~SmartPtr()
  10. {
  11. if (_ptr)
  12. delete _ptr;
  13. }
  14. T& operator*() { return *_ptr; }
  15. T* operator->() { return _ptr; }
  16. private:
  17. T* _ptr;
  18. };
  19. struct Date
  20. {
  21. int _year;
  22. int _month;
  23. int _day;
  24. };
  25. int main()
  26. {
  27. SmartPtr<int> sp1(new int);
  28. *sp1 = 10;
  29. cout << *sp1 << endl;
  30. SmartPtr<Date> sp2(new Date);
  31. (*sp2)._year = 2020; // sp2.operator*()._year;
  32. sp2->_year = 2021; // sp2.operator->()->_year;
  33. return 0;
  34. }

三,C++库中的智能指针

        C++库中的智能指针都定义在头文件<memory>中;

auto_ptr

  • 此模板为指针提供了一个有限的垃圾回功能,在auto_ptr对象销毁时自动回收指向的内存;
  • C++98,当拷贝或赋值auto_ptr对象时,被拷贝或赋值对象就销毁释放了;
  • C++11,此模板已废弃,使用具有类似功能的新模板unique_ptr(提升了安全性);
  1. #include<iostream>
  2. #include<memory>
  3. using namespace std;
  4. int main()
  5. {
  6. auto_ptr<int> ap1(new int);
  7. *ap1 = 10;
  8. auto_ptr<int> ap2(ap1); //拷贝构造后,ap1即销毁
  9. auto_ptr<int> ap3(new int);
  10. ap3 = ap2; //赋值后,ap2即销毁
  11. return 0;
  12. }

  •  实现原理,管理权移交思想;
  1. template<class T>
  2. class AutoPtr
  3. {
  4. public:
  5. AutoPtr(T* ptr = NULL)
  6. :_ptr(ptr)
  7. {}
  8. ~AutoPtr()
  9. {
  10. if (_ptr)
  11. delete _ptr;
  12. }
  13. AutoPtr(AutoPtr<T>& ap)
  14. :_ptr(ap._ptr)
  15. {
  16. ap._ptr = NULL;
  17. }
  18. AutoPtr<T>& operator=(AutoPtr<T>& ap)
  19. {
  20. if (this != &ap)
  21. {
  22. if (_ptr)
  23. delete _ptr;
  24. _ptr = ap._ptr;
  25. ap._ptr = NULL;
  26. }
  27. return *this;
  28. }
  29. private:
  30. T* _ptr;
  31. };

unique _ptr

  • 此模板为指针提供了一个有限的垃圾回收功能,与内置的指针相比几乎没有额外的开销;
  • 自身销毁时、operator=或显式调用reset使其值发生更改时,都会使用deleter自动删除其管理的对象;
  • 此模板类有两个成员:pointer(可使用get/release访问)、deleter(可使用get_deleter访问);
  • unique_ptr对象复制了有限的指针功能,通过*、->、[ ]管理对象;为安全起见,不支持指针算法,只支持移动赋值(禁止拷贝赋值);
  1. //为安全起见,不支持拷贝和赋值
  2. unique_ptr (const unique_ptr&) = delete;
  3. unique_ptr& operator= (const unique_ptr&) = delete;
  4. //支持移动构造
  5. unique_ptr (unique_ptr&& x) noexcept;
  6. unique_ptr& operator= (unique_ptr&& x) noexcept;
  1. int main()
  2. {
  3. unique_ptr<int> up1(new int), up2(new int);
  4. *up1 = 10, *up2 = 20;
  5. up1 = move(up2);
  6. up1.reset(new int);
  7. auto up3 = unique_ptr<int>(up1.get());
  8. up3.release();
  9. up1.get_deleter()(up1.get());
  10. return 0;
  11. }
  • 实现原理,简单粗暴防拷贝;
  1. template<class T>
  2. class UniquePtr
  3. {
  4. public:
  5. UniquePtr(T* ptr = nullptr)
  6. :_ptr(ptr)
  7. {}
  8. ~UniquePtr()
  9. {
  10. if (_ptr)
  11. delete _ptr;
  12. }
  13. T& operator*() { return *_ptr };
  14. T& operator->() { return _ptr };
  15. private:
  16. //C++98防拷贝方式,只私有声明不实现
  17. UniquePtr(UniquePtr<T> const&);
  18. UniquePtr& operator=(UniquePtr<T> const&);
  19. //C++11防拷贝方式,delete
  20. UniquePtr(UniquePtr<T> const&) = delete;
  21. UniquePtr& operator=(UniquePtr<T> const&) = delete;
  22. private:
  23. T* _ptr;
  24. };

shared_ptr

  • 此模板为指针提供了一个有限的垃圾回收功能,可与其他对象共享管理;
  • 此类对象可获取和共享指针的所有权,最后一个所有者负责释放;
  • 自身销毁时、operator=或显式调用reset使其值发生更改时,就会释放共享对象的所有权;当所有对象都释放了所有权,就会使用deleter删除其管理的对象;
  • 此类对象只能通过拷贝shared_ptr对象来共享所有权,如通过同一指针(非共享指针)构建的对象,则不会共享,会造成一个对象释放时,另一个对象无处释放;
  • shared_ptr对象关联两个指针:stored pointerowned pointer;通常它们关联相同对象,但alias构造时,会不同;
  • 不拥有所有权的指针为empty shared_ptr,不指向任何对象的指针为null shared_ptr;empty shared_ptr不一定是null shared_ptr,null shared_ptr也不一定是empty shared_ptr;
  • shared_ptr对象复制了有限的指针功能,通过*、->访问所指对象;为安全起见,不支持指针算法;
  1. auto ptr = new int;
  2. //共享同一块空间,共享所有权
  3. shared_ptr<int> ptr1(ptr);
  4. shared_ptr<int> ptr2(ptr1);
  5. //共享同一块空间,但不共享所有权
  6. shared_ptr<int> ptr1(ptr);
  7. shared_ptr<int> ptr2(ptr);

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

  • shared_ptr在其内部,给每个资源都维护着一份计数,用来记录该份资源被几个对象共享;
  • 在对象被销毁时(析构),说明该资源不使用了,引用计数减1;
  • 如引用计数为0,说明是最后一个使用该资源的对象,必须释放该资源;
  • 如引用计数不为0,说明还有对象在使用该资源,不可释放,否则成野指针;
  1. template<class T>
  2. class SharedPtr
  3. {
  4. public:
  5. SharedPtr(T* ptr=nullptr)
  6. :_ptr(ptr)
  7. ,_pRefCount(new int(1))
  8. ,_pMutex(new mutex)
  9. {}
  10. ~SharedPtr()
  11. {
  12. Release();
  13. }
  14. SharedPtr(const SharedPtr<T>& sp)
  15. :_ptr(sp._ptr)
  16. , _pRefCount(sp._pRefCount)
  17. , _pMutex(sp._pMutex)
  18. {
  19. AddRefCount();
  20. }
  21. SharedPtr<T>& operator=(const SharedPtr<T>& sp)
  22. {
  23. if (_ptr != sp._ptr)
  24. {
  25. Release();
  26. _ptr = sp._ptr;
  27. _pRefCount(sp._pRefCount);
  28. _pMutex(sp._pMutex);
  29. AddRefCount();
  30. }
  31. return *this;
  32. }
  33. T& operator*() { return *_ptr; }
  34. T* operator->() { return _ptr; }
  35. int UseCount() { return *_pRefCount; }
  36. T* Get() { return _ptr };
  37. void AddRefCount()
  38. {
  39. _pMutex->lock();
  40. ++(*_pRefCount);
  41. _pMutex->unlock();
  42. }
  43. private:
  44. void Release()
  45. {
  46. bool deleteflag = false;
  47. _pMutex.lock();
  48. if (--(*_pRefCount == 0))
  49. {
  50. delete _ptr;
  51. delete _pRefCount;
  52. deleteflag = true;
  53. }
  54. if (deleteflag == true)
  55. delete _pMutex;
  56. }
  57. private:
  58. T* _ptr;
  59. int* _pRefCount;
  60. mutex* _pMutex; // 互斥锁
  61. };

shared_ptr线程安全问题

  • 智能指针对象中引用计数是多个智能指针对象共享的,两个线程中智能指针的引用计数同时++或--,引用计数原来是1,++两次可能还是2,这样引用计数就错乱了,会导致资源未释放或程序崩溃;所以智能指针中引用计数++或--是需要加锁的,也就是说引用计数的操作是线程安全的;
  • 智能指针管理的对象存放在堆上,两个线程同时去访问,会导致线程安全问题;

shared_ptr循环引用

  1. struct listnode
  2. {
  3. ~listnode() { cout << "~listnode()" << endl; }
  4. int _data;
  5. shared_ptr<listnode> _prev;
  6. shared_ptr<listnode> _next;
  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. }
  • 两个智能指针对象node1、node2,指向两个节点,引用计数变成1,不需手动delete;
  • node1->_next指向node2,node2->_next指向node1,引用计数变成2;
  • node1/node2析构,引用计数减到1,但是_next还指向下一个节点,_prev还指向上个节点;也就是说_next析构了,node2就释放,_prev析构了,node1就释放;
  • 但是_next属于node的成员,node2释放了,_next才会析构,而node1由_prev管理,_prev属于node2成员,所以这就叫循环引用,谁也不会释放;
  • 针对上述问题,可使用weak_ptr;

weak_ptr

  • 一种弱引用的智能指针类型,可用于解决shared_ptr循环引用的问题;
  • 使用weak_ptr,不会增加引用计数;
  1. struct listnode
  2. {
  3. ~listnode() { cout << "~listnode()" << endl; }
  4. int _data;
  5. weak_ptr<listnode> _prev;
  6. weak_ptr<listnode> _next;
  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. }

如不是new出来的对象,使用删除器;

  1. //仿函数删除器
  2. template<class T>
  3. struct FreeFunc
  4. {
  5. void operator()(T* ptr)
  6. {
  7. cout << "free:" << ptr << endl;
  8. free(ptr);
  9. }
  10. };
  11. template<class T>
  12. struct DeleteArrayFunc
  13. {
  14. void operator()(T* ptr)
  15. {
  16. cout << "delete[]:" << ptr << endl;
  17. delete[] ptr;
  18. }
  19. };
  20. int main()
  21. {
  22. FreeFunc<int> freefunc;
  23. shared_ptr<int> sp1((int*)malloc(4), freefunc);
  24. DeleteArrayFunc<int> deletearrayfunc;
  25. shared_ptr<int>sp2((int*)malloc(4), deletearrayfunc);
  26. }

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

  • C++98中产生了第一个智能指针auto_ptr;
  • C++boost给出了更加实用的scoped_ptr、shared_ptr、weak_ptr;
  • C++TR1,引入了shared_ptr等,但TR1不是标准版;
  • C++11,引入了unique_ptr、shared_ptr、weak_ptr,uniqu_ptr对应boost的scoped_ptr,且这些智能指针的实现原理参考了boost中的实现;

附:RAII扩展        

        RAII思想除了可以原来设计智能指针,还可以用来设计守卫锁,防止异常安全导致的死锁问题;

  1. #include<iostream>
  2. #include<thread>
  3. #include<mutex>
  4. using namespace std;
  5. template<class Mutex>
  6. class LockGuard
  7. {
  8. public:
  9. LockGuard(Mutex& mtx)
  10. :_mutex(mtx)
  11. {
  12. _mutex.lock();
  13. }
  14. ~LockGuard()
  15. {
  16. _mutex.unlock();
  17. }
  18. LockGuard(const LockGuard<Mutex>&) = delete;
  19. private:
  20. Mutex& _mutex; //必须使用引用
  21. };
  22. mutex mtx;
  23. static int n = 0;
  24. void Func()
  25. {
  26. for (size_t i = 0; i < 1000000; ++i)
  27. {
  28. LockGuard<mutex> lock(mtx);
  29. ++n;
  30. }
  31. }
  32. int main()
  33. {
  34. int begin = clock();
  35. thread t1(Func);
  36. thread t2(Func);
  37. t1.join();
  38. t2.join();
  39. int end = clock();
  40. cout << n << endl;
  41. cout << "cost time:" << end - begin << endl;
  42. }

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/爱喝兽奶帝天荒/article/detail/781550
推荐阅读
相关标签
  

闽ICP备14008679号