C++中智能指针的原理、使用、实现

矫情吗;* 2022-10-05 02:56 265阅读 0赞

d9ea4e14541419fb4ee505991140747b.gif

链接 | https://www.cnblogs.com/wxquare/p/4759020.html

1、智能指针的作用

C++程序设计中使用堆内存是非常频繁的操作,堆内存的申请和释放都由程序员自己管理。程序员自己管理堆内存可以提高了程序的效率,但是整体来说堆内存的管理是麻烦的,C++11中引入了智能指针的概念,方便管理堆内存。使用普通指针,容易造成堆内存泄露(忘记释放),二次释放,程序发生异常时内存泄露等问题等,使用智能指针能更好的管理堆内存。

理解智能指针需要从下面三个层次:

1、从较浅的层面看,智能指针是利用了一种叫做RAII(资源获取即初始化)的技术对普通的指针进行封装,这使得智能指针实质是一个对象,行为表现的却像一个指针。

2、智能指针的作用是防止忘记调用delete释放内存和程序异常的进入catch块忘记释放内存。另外指针的释放时机也是非常有考究的,多次释放同一个指针会造成程序崩溃,这些都可以通过智能指针来解决。

3、智能指针还有一个作用是把值语义转换成引用语义。C++和Java有一处最大的区别在于语义不同,在Java里面下列代码:

Animal a = new Animal();
Animal b = a;

你当然知道,这里其实只生成了一个对象,a和b仅仅是把持对象的引用而已。但在C++中不是这样,

Animal a;
Animal b = a;

这里却是就是生成了两个对象。

关于值语言参考这篇文章http://www.cnblogs.com/Solstice/archive/2011/08/16/2141515.html

2、智能指针的使用

智能指针在C++11版本之后提供,包含在头文件中,shared_ptr、unique_ptr、weak_ptr

2.1 shared_ptr的使用

shared_ptr多个指针指向相同的对象。shared_ptr使用引用计数,每一个shared_ptr的拷贝都指向相同的内存。每使用他一次,内部的引用计数加1,每析构一次,内部的引用计数减1,减为0时,自动删除所指向的堆内存。shared_ptr内部的引用计数是线程安全的,但是对象的读取需要加锁。

  • 初始化。智能指针是个模板类,可以指定类型,传入指针通过构造函数初始化。也可以使用make_shared函数初始化。不能将指针直接赋值给一个智能指针,一个是类,一个是指针。例如std::shared_ptr p4 = new int(1);的写法是错误的
  • 拷贝和赋值。拷贝使得对象的引用计数增加1,赋值使得原对象引用计数减1,当计数为0时,自动释放内存。后来指向的对象引用计数加1,指向后来的对象
  • get函数获取原始指针
  • 注意不要用一个原始指针初始化多个shared_ptr,否则会造成二次释放同一内存
  • 注意避免循环引用,shared_ptr的一个最大的陷阱是循环引用,循环,循环引用会导致堆内存无法正确释放,导致内存泄漏。循环引用在weak_ptr中介绍。

    include

    include

    int main() {

    1. {
    2. int a = 10;
    3. std::shared_ptr<int> ptra = std::make_shared<int>(a);
    4. std::shared_ptr<int> ptra2(ptra); //copy
    5. std::cout << ptra.use_count() << std::endl;
    6. int b = 20;
    7. int *pb = &a;
    8. //std::shared_ptr<int> ptrb = pb; //error
    9. std::shared_ptr<int> ptrb = std::make_shared<int>(b);
    10. ptra2 = ptrb; //assign
    11. pb = ptrb.get(); //获取原始指针
    12. std::cout << ptra.use_count() << std::endl;
    13. std::cout << ptrb.use_count() << std::endl;
    14. }

    }

2.2 unique_ptr的使用

unique_ptr“唯一”拥有其所指对象,同一时刻只能有一个unique_ptr指向给定对象(通过禁止拷贝语义、只有移动语义来实现)。相比与原始指针unique_ptr用于其RAII的特性,使得在出现异常的情况下,动态资源能得到释放。unique_ptr指针本身的生命周期:从unique_ptr指针创建时开始,直到离开作用域。离开作用域时,若其指向对象,则将其所指对象销毁(默认使用delete操作符,用户可指定其他操作)。unique_ptr指针与其所指对象的关系:在智能指针生命周期内,可以改变智能指针所指对象,如创建智能指针时通过构造函数指定、通过reset方法重新指定、通过release方法释放所有权、通过移动语义转移所有权。

  1. #include <iostream>
  2. #include <memory>
  3. int main() {
  4. {
  5. std::unique_ptr<int> uptr(new int(10)); //绑定动态对象
  6. //std::unique_ptr<int> uptr2 = uptr; //不能賦值
  7. //std::unique_ptr<int> uptr2(uptr); //不能拷貝
  8. std::unique_ptr<int> uptr2 = std::move(uptr); //轉換所有權
  9. uptr2.release(); //释放所有权
  10. }
  11. //超過uptr的作用域,內存釋放
  12. }

2.3 weak_ptr的使用

weak_ptr是为了配合shared_ptr而引入的一种智能指针,因为它不具有普通指针的行为,没有重载operator*和->,它的最大作用在于协助shared_ptr工作,像旁观者那样观测资源的使用情况。weak_ptr可以从一个shared_ptr或者另一个weak_ptr对象构造,获得资源的观测权。但weak_ptr没有共享资源,它的构造不会引起指针引用计数的增加。使用weak_ptr的成员函数use_count()可以观测资源的引用计数,另一个成员函数expired()的功能等价于use_count()==0,但更快,表示被观测的资源(也就是shared_ptr的管理的资源)已经不复存在。weak_ptr可以使用一个非常重要的成员函数lock()从被观测的shared_ptr获得一个可用的shared_ptr对象, 从而操作资源。但当expired()==true的时候,lock()函数将返回一个存储空指针的shared_ptr。

  1. #include <iostream>
  2. #include <memory>
  3. int main() {
  4. {
  5. std::shared_ptr<int> sh_ptr = std::make_shared<int>(10);
  6. std::cout << sh_ptr.use_count() << std::endl;
  7. std::weak_ptr<int> wp(sh_ptr);
  8. std::cout << wp.use_count() << std::endl;
  9. if(!wp.expired()){
  10. std::shared_ptr<int> sh_ptr2 = wp.lock(); //get another shared_ptr
  11. *sh_ptr = 100;
  12. std::cout << wp.use_count() << std::endl;
  13. }
  14. }
  15. //delete memory
  16. }

2.4 循环引用

考虑一个简单的对象建模——家长与子女:a Parent has a Child, a Child knowshis/her Parent。在Java 里边很好写,不用担心内存泄漏,也不用担心空悬指针,只要正确初始化myChild 和myParent,那么Java 程序员就不用担心出现访问错误。一个handle 是否有效,只需要判断其是否non null。

  1. public class Parent
  2. {
  3.   private Child myChild;
  4. }
  5. public class Child
  6. {
  7.   private Parent myParent;
  8. }

在C++里边就要为资源管理费一番脑筋。如果使用原始指针作为成员,Child和Parent由谁释放?那么如何保证指针的有效性?如何防止出现空悬指针?这些问题是C++面向对象编程麻烦的问题,现在可以借助smart pointer把对象语义(pointer)转变为值(value)语义,shared_ptr轻松解决生命周期的问题,不必担心空悬指针。但是这个模型存在循环引用的问题,注意其中一个指针应该为weak_ptr。

原始指针的做法,容易出错

  1. #include <iostream>
  2. #include <memory>
  3. class Child;
  4. class Parent;
  5. class Parent {
  6. private:
  7. Child* myChild;
  8. public:
  9. void setChild(Child* ch) {
  10. this->myChild = ch;
  11. }
  12. void doSomething() {
  13. if (this->myChild) {
  14. }
  15. }
  16. ~Parent() {
  17. delete myChild;
  18. }
  19. };
  20. class Child {
  21. private:
  22. Parent* myParent;
  23. public:
  24. void setPartent(Parent* p) {
  25. this->myParent = p;
  26. }
  27. void doSomething() {
  28. if (this->myParent) {
  29. }
  30. }
  31. ~Child() {
  32. delete myParent;
  33. }
  34. };
  35. int main() {
  36. {
  37. Parent* p = new Parent;
  38. Child* c = new Child;
  39. p->setChild(c);
  40. c->setPartent(p);
  41. delete c; //only delete one
  42. }
  43. return 0;
  44. }

循环引用内存泄露的问题

  1. #include <iostream>
  2. #include <memory>
  3. class Child;
  4. class Parent;
  5. class Parent {
  6. private:
  7. std::shared_ptr<Child> ChildPtr;
  8. public:
  9. void setChild(std::shared_ptr<Child> child) {
  10. this->ChildPtr = child;
  11. }
  12. void doSomething() {
  13. if (this->ChildPtr.use_count()) {
  14. }
  15. }
  16. ~Parent() {
  17. }
  18. };
  19. class Child {
  20. private:
  21. std::shared_ptr<Parent> ParentPtr;
  22. public:
  23. void setPartent(std::shared_ptr<Parent> parent) {
  24. this->ParentPtr = parent;
  25. }
  26. void doSomething() {
  27. if (this->ParentPtr.use_count()) {
  28. }
  29. }
  30. ~Child() {
  31. }
  32. };
  33. int main() {
  34. std::weak_ptr<Parent> wpp;
  35. std::weak_ptr<Child> wpc;
  36. {
  37. std::shared_ptr<Parent> p(new Parent);
  38. std::shared_ptr<Child> c(new Child);
  39. p->setChild(c);
  40. c->setPartent(p);
  41. wpp = p;
  42. wpc = c;
  43. std::cout << p.use_count() << std::endl; // 2
  44. std::cout << c.use_count() << std::endl; // 2
  45. }
  46. std::cout << wpp.use_count() << std::endl; // 1
  47. std::cout << wpc.use_count() << std::endl; // 1
  48. return 0;
  49. }

正确的做法

  1. #include <iostream>
  2. #include <memory>
  3. class Child;
  4. class Parent;
  5. class Parent {
  6. private:
  7. //std::shared_ptr<Child> ChildPtr;
  8. std::weak_ptr<Child> ChildPtr;
  9. public:
  10. void setChild(std::shared_ptr<Child> child) {
  11. this->ChildPtr = child;
  12. }
  13. void doSomething() {
  14. //new shared_ptr
  15. if (this->ChildPtr.lock()) {
  16. }
  17. }
  18. ~Parent() {
  19. }
  20. };
  21. class Child {
  22. private:
  23. std::shared_ptr<Parent> ParentPtr;
  24. public:
  25. void setPartent(std::shared_ptr<Parent> parent) {
  26. this->ParentPtr = parent;
  27. }
  28. void doSomething() {
  29. if (this->ParentPtr.use_count()) {
  30. }
  31. }
  32. ~Child() {
  33. }
  34. };
  35. int main() {
  36. std::weak_ptr<Parent> wpp;
  37. std::weak_ptr<Child> wpc;
  38. {
  39. std::shared_ptr<Parent> p(new Parent);
  40. std::shared_ptr<Child> c(new Child);
  41. p->setChild(c);
  42. c->setPartent(p);
  43. wpp = p;
  44. wpc = c;
  45. std::cout << p.use_count() << std::endl; // 2
  46. std::cout << c.use_count() << std::endl; // 1
  47. }
  48. std::cout << wpp.use_count() << std::endl; // 0
  49. std::cout << wpc.use_count() << std::endl; // 0
  50. return 0;
  51. }

3、智能指针的设计和实现

下面是一个简单智能指针的demo。智能指针类将一个计数器与类指向的对象相关联,引用计数跟踪该类有多少个对象共享同一指针。每次创建类的新对象时,初始化指针并将引用计数置为1;当对象作为另一对象的副本而创建时,拷贝构造函数拷贝指针并增加与之相应的引用计数;对一个对象进行赋值时,赋值操作符减少左操作数所指对象的引用计数(如果引用计数为减至0,则删除对象),并增加右操作数所指对象的引用计数;调用析构函数时,构造函数减少引用计数(如果引用计数减至0,则删除基础对象)。智能指针就是模拟指针动作的类。所有的智能指针都会重载 -> 和 * 操作符。智能指针还有许多其他功能,比较有用的是自动销毁。这主要是利用栈对象的有限作用域以及临时对象(有限作用域实现)析构函数释放内存。

  1. 1 #include <iostream>
  2. 2 #include <memory>
  3. 3
  4. 4 template<typename T>
  5. 5 class SmartPointer {
  6. 6 private:
  7. 7 T* _ptr;
  8. 8 size_t* _count;
  9. 9 public:
  10. 10 SmartPointer(T* ptr = nullptr) :
  11. 11 _ptr(ptr) {
  12. 12 if (_ptr) {
  13. 13 _count = new size_t(1);
  14. 14 } else {
  15. 15 _count = new size_t(0);
  16. 16 }
  17. 17 }
  18. 18
  19. 19 SmartPointer(const SmartPointer& ptr) {
  20. 20 if (this != &ptr) {
  21. 21 this->_ptr = ptr._ptr;
  22. 22 this->_count = ptr._count;
  23. 23 (*this->_count)++;
  24. 24 }
  25. 25 }
  26. 26
  27. 27 SmartPointer& operator=(const SmartPointer& ptr) {
  28. 28 if (this->_ptr == ptr._ptr) {
  29. 29 return *this;
  30. 30 }
  31. 31
  32. 32 if (this->_ptr) {
  33. 33 (*this->_count)--;
  34. 34 if (this->_count == 0) {
  35. 35 delete this->_ptr;
  36. 36 delete this->_count;
  37. 37 }
  38. 38 }
  39. 39
  40. 40 this->_ptr = ptr._ptr;
  41. 41 this->_count = ptr._count;
  42. 42 (*this->_count)++;
  43. 43 return *this;
  44. 44 }
  45. 45
  46. 46 T& operator*() {
  47. 47 assert(this->_ptr == nullptr);
  48. 48 return *(this->_ptr);
  49. 49
  50. 50 }
  51. 51
  52. 52 T* operator->() {
  53. 53 assert(this->_ptr == nullptr);
  54. 54 return this->_ptr;
  55. 55 }
  56. 56
  57. 57 ~SmartPointer() {
  58. 58 (*this->_count)--;
  59. 59 if (*this->_count == 0) {
  60. 60 delete this->_ptr;
  61. 61 delete this->_count;
  62. 62 }
  63. 63 }
  64. 64
  65. 65 size_t use_count(){
  66. 66 return *this->_count;
  67. 67 }
  68. 68 };
  69. 69
  70. 70 int main() {
  71. 71 {
  72. 72 SmartPointer<int> sp(new int(10));
  73. 73 SmartPointer<int> sp2(sp);
  74. 74 SmartPointer<int> sp3(new int(20));
  75. 75 sp2 = sp3;
  76. 76 std::cout << sp.use_count() << std::endl;
  77. 77 std::cout << sp3.use_count() << std::endl;
  78. 78 }
  79. 79 //delete operator
  80. 80 }

往期**推荐**

☞ 趣味设计模式881ceea85bb97e4c66a378cdcfa6485b.gif

☞ 音视频开发

☞ C++ 进阶a880aea4c9cf4041f9e96eb4491d6dc6.gif

☞ 超硬核 Qt1bf9f1bc59cd61af9808ec0ca9e0531a.gif

☞ 玩转 Linux

☞ GitHub 开源推荐61d92a98ad7c86a260723f37e6468cf0.gif

☞ 程序人生

关注公众号「高效程序员」????,一起优秀!

回复“1024”,送你一份程序员大礼包。

发表评论

表情:
评论列表 (有 0 条评论,265人围观)

还没有评论,来说两句吧...

相关阅读