• 智能指针介绍(C++)


    前言

            关于智能指针大家或多或少都有听说过,因为在C++中没有GC,所以存在很多内存泄露的风险,所以基于RAII思想设计出了,智能指针,智能指针经过了很多个版本的迭代,从刚开始在C++98中推出了auto_ptr,但是auto_ptr不好用,它的设计存在重大缺陷,又因为C++的官方库更新的很慢,所以在接下来的n年中,没有改进,但是有一群大佬绝大C++库太简陋了,所以就自己搞了一个非官方的社区,写了一个库叫做boost,它里面重新写了智能指针。(boost库里面还有很多的其它东西),scoped_ptr/scoped防拷贝版本。shared_ptr/shared_ptr引用计数版本weak_ptr-为了解决shared_ptr循环引用的问题。之后在C++11中官方引入了智能指针,参考boost的实现,稍微进行改进,其实C++11其它类似于右值引用移动语义等也是参考boost。unique_ptr:防拷贝版本,shared_ptr引用计数版本,weak_ptr解决shared_ptr循环引用的问题

    目录

    1.内存泄露 

    2.智能指针的使用及其原理

            2.1RAII

            2.2智能指针的原理

            2.3std::auto_ptr

            2.4std::uniqueptr 

            2.5shared_ptr

    3.全部代码


    1.内存泄露 

            详见内存泄露的危害 

    2.智能指针的使用及其原理

            2.1RAII

            RAII(Resource Acquisition Is Initialization)是一种利用 对象的声明周期来管理资源(如内存,文件句柄,网络连接,互斥量等等)的简单技术。

            在对象构造的时候获取资源,接着控制对资源的访问使之在对象的声明周期内始终保持有效,最后在对象生命周期结束之后通过调用析构函数来对资源进行释放。借此,我们实际上把管理资源的任务托管给了一个对象。这样做的好处有两个:

            1.不需要显示的释放资源

            2.采用这种方式,对象所需要的资源在其生命周期内始终有效。

    1. namespace qyy
    2. {
    3. //使用RAII思想设计的SmartPtr类
    4. template<class T>
    5. class SmartPtr
    6. {
    7. public:
    8. SmartPtr(T*ptr)
    9. :_ptr(ptr)
    10. {}
    11. ~SmartPtr()
    12. {
    13. delete _ptr;
    14. cout << "~SmartPtr()" << endl;
    15. private:
    16. T *_ptr;
    17. };
    18. }
    19. void Test()
    20. {
    21. int* p1 = new int(1);
    22. qyy::SmartPtr<int> sp1(p1);
    23. int* p2 = new int(8);
    24. qyy::SmartPtr<int> sp2(p2);
    25. }

            2.2智能指针的原理

            

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

    1. template<class T>
    2. class SmartPtr
    3. {
    4. public:
    5. SmartPtr(T*ptr)
    6. :_ptr(ptr)
    7. {}
    8. T& operator*()
    9. {
    10. return *(_ptr);
    11. }
    12. //重载*和->
    13. T* operator->()
    14. {
    15. return _ptr;
    16. }
    17. ~SmartPtr()
    18. {
    19. delete _ptr;
    20. cout << "~SmartPtr()" << endl;
    21. }
    22. private:
    23. T *_ptr;
    24. };
    1. struct Date
    2. {
    3. Date(int year = 1,int month = 1,int day = 0)
    4. :_year(year)
    5. ,_month(month)
    6. ,_day(day)
    7. {}
    8. int _year;
    9. int _month;
    10. int _day;
    11. };
    12. void TestSmartPtr()
    13. {
    14. int* p1 = new int(1);
    15. qyy::SmartPtr<int> sp1(p1);
    16. cout << *sp1 << endl;//像指针一样使用
    17. qyy::SmartPtrdate(new Date);
    18. //需要注意的是这里应该是date.operator->()->year = 1;
    19. //本来应该是date->->year这里语法上为了可读性省略了一个->
    20. cout << date->_month << endl;
    21. cout << date->_day << endl;
    22. }

            总的来说:智能指针的原理就是:利用RAII特性并且实现指针一样的行为 

            2.3std::auto_ptr

            std::auto_ptr介绍文档

            在C++98中就实现了auto_ptr的智能指针, 它采用管理权转移的思想,下面简化模拟实现了一

    份qyy::auto_ptr来了解它的原理。

           

    1. //简化版本
    2. //C++98管理权转移思想
    3. template<class T>
    4. class auto_ptr
    5. {
    6. public:
    7. auto_ptr(T*ptr)
    8. :_ptr(ptr)
    9. {}
    10. //管理权转移
    11. //拷贝构造的管理权转移
    12. auto_ptr(auto_ptr& ap)
    13. :_ptr(nullptr)
    14. {
    15. _ptr = ap._ptr;
    16. ap._ptr = nullptr;
    17. }
    18. //operator=的管理权转移
    19. auto_ptr& operator=(auto_ptr& ap)
    20. {
    21. delete _ptr;
    22. _ptr = nullptr;
    23. _ptr = ap._ptr;
    24. ap._ptr = nullptr;
    25. return *this;
    26. }
    27. T&operator*()
    28. {
    29. return *_ptr;
    30. }
    31. T* operator->()
    32. {
    33. return _ptr;
    34. }
    35. ~auto_ptr()
    36. {
    37. if(_ptr)//确保指针不为空
    38. delete _ptr;
    39. }
    40. private:
    41. T* _ptr;
    42. };

             //测试代码

            

    1. void Test1()
    2. {
    3. qyy::auto_ptr<int> p1(new int(90));
    4. qyy::auto_ptr<int> p2(p1);
    5. qyy::auto_ptr<int> p3(new int(20));
    6. p3 = p2;
    7. //进行控制权转移,缺陷原来的智能指针无法使用存在坑
    8. /**p1 = 10;
    9. cout << *p1 << endl;*/
    10. }

            由于auto_ptr的设计存在缺陷,如果使用它进行拷贝构造和赋值,原来的智能指针就不能用了,很明显这是存在很大的坑的,所以不太推荐使用。

            2.4std::uniqueptr 

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

            std::unique_ptr的介绍文档 

            unique_ptr的实现原理:简单粗暴的防拷贝,下面通过模拟实现的简化版本的unique_ptr来了解它的原理。 

            

    1. //unique_ptr的简化版本
    2. template<class T>
    3. class unique_ptr
    4. {
    5. public:
    6. unique_ptr(T*ptr)
    7. :_ptr(ptr)
    8. {}
    9. unique_ptr(unique_ptr& up) = delete;
    10. unique_ptr operator=(unique_ptr& up) = delete;
    11. //重载operator*和operator->
    12. T& operator*()
    13. {
    14. return *_ptr;
    15. }
    16. T* operator->()
    17. {
    18. return _ptr;
    19. }
    20. ~unique_ptr()
    21. {
    22. delete _ptr;
    23. }
    24. private:
    25. T* _ptr;
    26. };

            //测试代码

            

    1. void Test2()
    2. {
    3. qyy::unique_ptr<int> p1 (new int(30));
    4. //qyy::unique_ptr p2(p1);
    5. qyy::unique_ptr<int> p2(new int(40));
    6. //p1 = p2;
    7. //缺陷是无法拷贝构造和赋值
    8. }

            unique_ptr的缺陷就是无法拷贝构造和赋值

            2.5shared_ptr

            C++11还提供了一种可以进行拷贝构造和赋值的智能指针shared_ptr;

             std::shared_ptr介绍文档

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

            1.shared_ptr在其内部,给每个资源都维护着一份引用计数,用来记录该份资源被几个对象共享。

            2.在对象被销毁时(也就是析构函数调用的时候),就说明自己不使用该资源了,对象的引用计数减一

            3.如果引用计数是0,说明自己是最后一个使用该资源的对象,必须释放该资源;

            4.如果不是0,就说明除了自己还有别的人也在使用该资源,不能释放该资源,否则其他对象就成野指针了。 

    1. //引用计数支持多个资源拷贝管理同一个资源,最后一个析构对象释放资源
    2. template<class T>
    3. class shared_ptr
    4. {
    5. public:
    6. //构造函数,将资源交给对象管理
    7. shared_ptr(T*ptr)
    8. :_ptr(ptr)
    9. ,_pCount(new int(1))
    10. ,_pMutex(new mutex)
    11. {}
    12. //析构函数,对资源进行清理
    13. ~shared_ptr()
    14. {
    15. /*if (-- * _count == 0)
    16. {
    17. delete _ptr;
    18. delete _count;
    19. }*/
    20. release();
    21. }
    22. //拷贝构造,完成多个对象的资源共享
    23. shared_ptr(shared_ptr& sp)
    24. {
    25. _ptr = sp._ptr;
    26. _pCount = sp._pCount;
    27. _pMutex = sp._pMutex;
    28. //增加引用计数
    29. /*++*_count;*/
    30. AddRef();
    31. }
    32. shared_ptr& operator=(shared_ptr& sp)
    33. {
    34. if (this != &sp)
    35. {
    36. release();
    37. _ptr = sp._ptr;
    38. _pCount = sp._pCount;
    39. _pMutex = sp._pMutex;
    40. AddRef();
    41. }
    42. return *this;
    43. }
    44. //避免线程不安全
    45. void release()
    46. {
    47. bool flag = false;
    48. _pMutex->lock();
    49. if (-- * _pCount == 0)//需要将之前所管理的资源进行释放
    50. {
    51. delete _ptr;
    52. delete _pCount;
    53. flag = true;
    54. }
    55. _pMutex->unlock();
    56. if (flag)
    57. delete _pMutex;
    58. }
    59. //避免出现线程安全问题
    60. void AddRef()
    61. {
    62. _pMutex->lock();//加锁
    63. ++(*_pCount);
    64. _pMutex->unlock();//解锁
    65. }
    66. //重载operator*和operator->
    67. T& operator*()
    68. {
    69. return *_ptr;
    70. }
    71. T* operator->()
    72. {
    73. return _ptr;
    74. }
    75. private:
    76. T* _ptr;
    77. int* _pCount;//引用计数
    78. mutex* _pMutex;//锁
    79. };

            测试代码:

    1. void Test3()
    2. {
    3. qyy::shared_ptr<int> sp1(new int(10));
    4. qyy::shared_ptr<int> sp2(sp1);
    5. qyy::shared_ptrint, int> > sp3(new pair<int,int>(1, 1) );
    6. cout << *sp1 << endl;
    7. cout << sp3->first << ":" << sp3->second << endl;
    8. //解决了防拷贝的缺点
    9. qyy::shared_ptr<int> sp4(new int(13));
    10. qyy::shared_ptr<int> sp5(new int(44));
    11. sp4 = sp5;
    12. //引用计数是线程安全的吗?
    13. }

              shared_ptr是线程安全的吗?

            是的,引用计数的加减是加锁保护的。但是指向的资源不是线程安全的。指向堆空间的资源的线程安全问题是访问的人处理的,智能指针不管,也管不到。引用计数的线程安全问题是智能指针要处理的。

            shared_ptr的线程安全问题

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

            1.    智能指针中的引用计数是多个智能指针对象共享的,两个线程中的引用计数同时++或者--,这个操作不是原子操作,引用计数原来是1,++两次,可能还是2,这样的引用计数就会错乱。会导致资源未释放或者程序崩溃的问题,所以对引用计数++或者--的时候要加锁。也就是说引用计数是线程安全的。

            2.智能指针管理的对象存放在堆上,两个线程同时去访问,会导致线程安全问题。

    1. // 演示引用计数线程安全问题,就把AddRefCount和SubRefCount中的锁去掉
    2. //线程安全是偶发性问题,main函数的n改的大一些概率就会变大
    3. //使用qyy::shared_ptr进行测试,为了方便验证引用计数的线程安全问题,可以使用官方库提供的shared_ptr,可以验证库里面的
    4. //shared_ptr,结论是一样的
    5. struct Date1
    6. {
    7. int _year = 0;
    8. int _month = 0;
    9. int _day = 0;
    10. };
    11. void SharePtrFunc(qyy::shared_ptr&sp,size_t n,mutex&mtu)
    12. {
    13. cout << sp.Count() << endl;
    14. for (size_t i = 0; i < n; ++i)
    15. {
    16. //这里智能指针拷贝会++计数,析构会--计数,这里是线程安全的
    17. qyy::shared_ptr copy(sp);
    18. //这里智能指针管理的资源不是线程安全的,
    19. {
    20. //unique_lock lk(mtu);//这里加锁这些资源的访问也就是线程安全的
    21. copy->_month++;
    22. copy->_year++;
    23. }
    24. //所以这些值虽然最终在主函数中调用时加了2n次,但是最终结果看到的并不是2n次
    25. }
    26. }
    27. int main()
    28. {
    29. qyy::shared_ptr p = new Date1;
    30. const size_t n = 100000;
    31. mutex mu;
    32. thread t1(SharePtrFunc, std::ref(p), n, std::ref(mu));
    33. thread t2(SharePtrFunc, std::ref(p), n, std::ref(mu));
    34. t1.join();
    35. t2.join();
    36. cout <<"day::" << p->_day << endl;
    37. cout << "month::"<_month << endl;
    38. cout << "year::" << p->_year << endl;
    39. cout << p.Count() << endl;
    40. return 0;
    41. }

       

            std::shared_ptr的循环引用

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

            循环引用分析:

            1.node1和node2两个智能指针对象分别指向两个节点,引用计数变为1,我们不需要手动delete。

            2.node1的_next指向node2,node2的_prev指向node1,引用计数变为2。

            3.node1和node2析构引用计数变为1,但是_next节点还指向下一个节点,_prev还指向上一个节点。

            4.也就是说_next析构了,node2就释放了,_prev析构了,node1就释放了。

            5.但是_next属于node成员,node1释放了_next才会释放,_prev属于node成员,node2释放了,_prev才会释放。现在是node1和node2谁都无法先释放,它们互相影响。所以这叫循环引用。谁都不会释放。

            因为只有当引用计数变为0时,申请的空间才会被释放掉,但是这里调用析构函数之后两块空间的引用计数都是1,并且node1中的_next指针管理着,node2的空间,node2的_prev指针管理着node1的空间,它们的空间都没有销毁所以空间里面的成员变量都没有调用析构函数,就会造成这样的问题。

            这里有一些抽象需要花一点时间来理解。

            解决方法:在引用计数的场景下,把节点中的_prev和_next改成weak_ptr就可以了。

            原理就是node1->_next = node2;和node2->_prev = node1;时,weak_ptr的next和_prev不会增加node1和node2的引用计数。因为weak_ptr不会增加引用计数。

            weak_ptr的实现: 

             

    1. template<class T>
    2. class weak_ptr
    3. {
    4. public:
    5. weak_ptr()
    6. :_ptr(nullptr)
    7. {}
    8. weak_ptr(const shared_ptr &sp)
    9. :_ptr(sp.get_ptr())
    10. {}
    11. weak_ptr & operator= (const shared_ptr& sp)
    12. {
    13. _ptr = sp.get_ptr();
    14. return *this;
    15. }
    16. T&operator*()
    17. {
    18. return _ptr;
    19. }
    20. T* operator->()
    21. {
    22. return &_ptr;
    23. }
    24. private:
    25. T* _ptr;
    26. };

            严格来说,weak_ptr不是智能指针,因为它不符合RAII的思想,它只是为了解决shared_ptr循环引用中的问题而设计出来的。weak_ptr不会增加引用计数。 

    3.全部代码

            //SmartPtr.hpp

    1. #include
    2. #include
    3. using namespace std;
    4. namespace qyy
    5. {
    6. template<class T>
    7. class SmartPtr
    8. {
    9. public:
    10. SmartPtr(T*ptr)
    11. :_ptr(ptr)
    12. {}
    13. T& operator*()
    14. {
    15. return *(_ptr);
    16. }
    17. T* operator->()
    18. {
    19. return _ptr;
    20. }
    21. ~SmartPtr()
    22. {
    23. delete _ptr;
    24. cout << "~SmartPtr()" << endl;
    25. }
    26. //指针无法拷贝和赋值
    27. //所以要禁用掉
    28. SmartPtr&operator=(const SmartPtr& sp) = delete;
    29. SmartPtr(const SmartPtr& sp) = delete;
    30. private:
    31. T *_ptr;
    32. };
    33. template<class T>
    34. class auto_ptr
    35. {
    36. public:
    37. auto_ptr(T*ptr)
    38. :_ptr(ptr)
    39. {}
    40. //管理权转移
    41. //拷贝构造的管理权转移
    42. auto_ptr(auto_ptr& ap)
    43. :_ptr(nullptr)
    44. {
    45. _ptr = ap._ptr;
    46. ap._ptr = nullptr;
    47. }
    48. //operator=的管理权转移
    49. auto_ptr& operator=(auto_ptr& ap)
    50. {
    51. delete _ptr;
    52. _ptr = nullptr;
    53. _ptr = ap._ptr;
    54. ap._ptr = nullptr;
    55. return *this;
    56. }
    57. T&operator*()
    58. {
    59. return *_ptr;
    60. }
    61. T* operator->()
    62. {
    63. return _ptr;
    64. }
    65. ~auto_ptr()
    66. {
    67. if(_ptr)//确保指针不为空
    68. delete _ptr;
    69. }
    70. private:
    71. T* _ptr;
    72. };
    73. template<class T>
    74. class unique_ptr
    75. {
    76. public:
    77. unique_ptr(T*ptr)
    78. :_ptr(ptr)
    79. {}
    80. unique_ptr(unique_ptr& up) = delete;
    81. unique_ptr operator=(unique_ptr& up) = delete;
    82. //重载operator*和operator->
    83. T& operator*()
    84. {
    85. return *_ptr;
    86. }
    87. T* operator->()
    88. {
    89. return _ptr;
    90. }
    91. ~unique_ptr()
    92. {
    93. delete _ptr;
    94. }
    95. private:
    96. T* _ptr;
    97. };
    98. //引用计数支持多个资源拷贝管理同一个资源,最后一个析构对象释放资源
    99. template<class T>
    100. class shared_ptr
    101. {
    102. public:
    103. //构造函数,将资源交给对象管理
    104. shared_ptr(T*ptr = nullptr)
    105. :_ptr(ptr)
    106. ,_pCount(new int(1))
    107. ,_pMutex(new mutex)
    108. {}
    109. //析构函数,对资源进行清理
    110. ~shared_ptr()
    111. {
    112. /*if (-- * _count == 0)
    113. {
    114. delete _ptr;
    115. delete _count;
    116. }*/
    117. release();
    118. }
    119. //拷贝构造,完成多个对象的资源共享
    120. shared_ptr(shared_ptr& sp)
    121. {
    122. _ptr = sp._ptr;
    123. _pCount = sp._pCount;
    124. _pMutex = sp._pMutex;
    125. //增加引用计数
    126. /*++*_count;*/
    127. AddRef();
    128. }
    129. shared_ptr& operator=(shared_ptr& sp)
    130. {
    131. if (this != &sp)
    132. {
    133. release();
    134. _ptr = sp._ptr;
    135. _pCount = sp._pCount;
    136. _pMutex = sp._pMutex;
    137. AddRef();
    138. }
    139. return *this;
    140. }
    141. int Count()
    142. {
    143. return *_pCount;
    144. }
    145. //避免线程不安全
    146. void release()
    147. {
    148. bool flag = false;
    149. _pMutex->lock();
    150. if (-- * _pCount == 0)//需要将之前所管理的资源进行释放
    151. {
    152. delete _ptr;
    153. delete _pCount;
    154. flag = true;
    155. }
    156. _pMutex->unlock();
    157. if (flag)
    158. delete _pMutex;
    159. }
    160. //避免出现线程安全问题
    161. void AddRef()
    162. {
    163. _pMutex->lock();//加锁
    164. ++(*_pCount);
    165. _pMutex->unlock();//解锁
    166. }
    167. T* get_ptr()const
    168. {
    169. return _ptr;
    170. }
    171. //重载operator*和operator->
    172. T& operator*()
    173. {
    174. return *_ptr;
    175. }
    176. T* operator->()
    177. {
    178. return _ptr;
    179. }
    180. private:
    181. T* _ptr;
    182. int* _pCount;//引用计数
    183. mutex* _pMutex;//锁
    184. };
    185. template<class T>
    186. class weak_ptr
    187. {
    188. public:
    189. weak_ptr()
    190. :_ptr(nullptr)
    191. {}
    192. weak_ptr(const shared_ptr &sp)
    193. :_ptr(sp.get_ptr())
    194. {}
    195. weak_ptr & operator= (const shared_ptr& sp)
    196. {
    197. _ptr = sp.get_ptr();
    198. return *this;
    199. }
    200. T&operator*()
    201. {
    202. return _ptr;
    203. }
    204. T* operator->()
    205. {
    206. return &_ptr;
    207. }
    208. private:
    209. T* _ptr;
    210. };
    211. }

            //Test.cpp 

    1. #include"SmartPtr.hpp"
    2. struct Date
    3. {
    4. Date(int year = 1,int month = 1,int day = 0)
    5. :_year(year)
    6. ,_month(month)
    7. ,_day(day)
    8. {}
    9. int _year;
    10. int _month;
    11. int _day;
    12. };
    13. void TestSmartPtr()
    14. {
    15. int* p1 = new int(1);
    16. qyy::SmartPtr<int> sp1(p1);
    17. cout << *sp1 << endl;//像指针一样使用
    18. qyy::SmartPtrdate(new Date);
    19. //需要注意的是这里应该是date.operator->()->year = 1;
    20. //本来应该是date->->year这里语法上为了可读性省略了一个->
    21. cout << date->_month << endl;
    22. cout << date->_day << endl;
    23. }
    24. void Test()
    25. {
    26. int* p1 = new int(1);
    27. qyy::SmartPtr<int> sp1(p1);
    28. int* p2 = new int(8);
    29. qyy::SmartPtr<int> sp2(p2);
    30. //sp2 = sp1;
    31. //缺陷是如果进行智能指针的拷贝构造和赋值程序会崩溃
    32. //qyy::SmartPtr p2(p1);
    33. cout << *sp1<< endl;
    34. }
    35. void Test1()
    36. {
    37. qyy::auto_ptr<int> p1(new int(90));
    38. qyy::auto_ptr<int> p2(p1);
    39. qyy::auto_ptr<int> p3(new int(20));
    40. p3 = p2;
    41. //进行控制权转移,缺陷原来的智能指针无法使用存在坑
    42. /**p1 = 10;
    43. cout << *p1 << endl;*/
    44. }
    45. void Test2()
    46. {
    47. qyy::unique_ptr<int> p1 (new int(30));
    48. //qyy::unique_ptr p2(p1);
    49. qyy::unique_ptr<int> p2(new int(40));
    50. //p1 = p2;
    51. //缺陷是无法拷贝构造和赋值
    52. }
    53. void Test3()
    54. {
    55. qyy::shared_ptr<int> sp1(new int(10));
    56. qyy::shared_ptr<int> sp2(sp1);
    57. qyy::shared_ptrint, int> > sp3(new pair<int,int>(1, 1) );
    58. cout << *sp1 << endl;
    59. cout << sp3->first << ":" << sp3->second << endl;
    60. //解决了防拷贝的缺点
    61. qyy::shared_ptr<int> sp4(new int(13));
    62. qyy::shared_ptr<int> sp5(new int(44));
    63. sp4 = sp5;
    64. //引用计数是线程安全的吗?
    65. }
    66. #include
    67. void Test4()
    68. {
    69. int n = 10;
    70. for (int i = 0; i < 100; ++i)
    71. {
    72. thread t1([]() {
    73. qyy::shared_ptr<int> sp1(new int(10));
    74. cout << sp1.Count() << endl;
    75. });
    76. t1.join();
    77. }
    78. }
    79. // 演示引用计数线程安全问题,就把AddRefCount和SubRefCount中的锁去掉
    80. //线程安全是偶发性问题,main函数的n改的大一些概率就会变大
    81. //使用qyy::shared_ptr进行测试,为了方便验证引用计数的线程安全问题,可以使用官方库提供的shared_ptr,可以验证库里面的
    82. //shared_ptr,结论是一样的
    83. struct Date1
    84. {
    85. int _year = 0;
    86. int _month = 0;
    87. int _day = 0;
    88. };
    89. void SharePtrFunc(qyy::shared_ptr&sp,size_t n,mutex&mtu)
    90. {
    91. cout << sp.Count() << endl;
    92. for (size_t i = 0; i < n; ++i)
    93. {
    94. //这里智能指针拷贝会++计数,析构会--计数,这里是线程安全的
    95. qyy::shared_ptr copy(sp);
    96. //这里智能指针管理的资源不是线程安全的,
    97. {
    98. //unique_lock lk(mtu);//这里加锁这些资源的访问也就是线程安全的
    99. copy->_day++;
    100. copy->_month++;
    101. copy->_year++;
    102. }
    103. //所以这些值虽然最终在主函数中调用时加了2n次,但是最终结果看到的并不是2n次
    104. }
    105. }
    106. int main1()
    107. {
    108. qyy::shared_ptr p = new Date1;
    109. const size_t n = 10000000;
    110. mutex mu;
    111. thread t1(SharePtrFunc, std::ref(p), n, std::ref(mu));
    112. thread t2(SharePtrFunc, std::ref(p), n, std::ref(mu));
    113. t1.join();
    114. t2.join();
    115. cout <<"day::" << p->_day << endl;
    116. cout << "month::"<_month << endl;
    117. cout << "year::" << p->_year << endl;
    118. cout << p.Count() << endl;
    119. return 0;
    120. }
    121. struct ListNode
    122. {
    123. int _data;
    124. qyy::weak_ptr_prev;
    125. qyy::weak_ptr_next;
    126. ~ListNode()
    127. {
    128. cout << "~ListNode" << endl;
    129. }
    130. };
    131. int main()
    132. {
    133. qyy::shared_ptr node1(new ListNode);
    134. qyy::shared_ptr node2(new ListNode);
    135. cout << node1.Count() << endl;
    136. cout << node2.Count() << endl;
    137. node1->_next = node2;
    138. node2->_prev = node1;
    139. cout << node1.Count() << endl;
    140. cout << node2.Count() << endl;
    141. return 0;
    142. }

  • 相关阅读:
    C++练习:类和对象
    三、【VUE-CLI】修改默认配置
    vue生命周期钩子函数
    Linux小知识---子进程与线程的一些知识点
    暖通锅炉远程监控解决方案
    重温c语言九----函数的学习
    HTML做一个简单的页面(纯html代码)地球专题学习网站
    计算机网络 MAC地址表管理
    Promise从入门到精通(第4章 async 和 await)
    自动驾驶——为什么需要仿真?
  • 原文地址:https://blog.csdn.net/m0_68641696/article/details/132965285