1. /*! @share_ptr.cpp
    2. * 实现share_ptr智能指针
    3. * wang_haolin
    4. * 2022/7/5
    5. */
    6. #include<iostream>
    7. #include<mutex>
    8. using namespace std;
    9. template<class T>
    10. class CSharePtr
    11. {
    12. public:
    13. CSharePtr(T* ptr = nullptr) :
    14. m_pPtr(ptr),
    15. m_nConunt(new int(1)),
    16. m_xMutex(new mutex)
    17. {}
    18. ~CSharePtr()
    19. {
    20. Release();
    21. }
    22. CSharePtr(const CSharePtr<T>& sp)
    23. {
    24. m_pPtr = sp.m_pPtr;
    25. m_nConunt = sp.m_nConunt;
    26. m_xMutex = sp.m_xMutex;
    27. AddRefCount();
    28. }
    29. CSharePtr<T>& operator=(const CSharePtr<T> sp)
    30. { // 赋值引用计数+1
    31. if (sp.m_pPtr != m_pPtr)
    32. { // 释放旧有资源
    33. Release();
    34. m_pPtr = sp.m_pPtr;
    35. m_nConunt = sp.m_nConunt;
    36. m_xMutex = sp.m_xMutex;
    37. AddRefCount();
    38. }
    39. return *this;
    40. }
    41. T& operator*()
    42. {
    43. return *m_pPtr;
    44. }
    45. T* operator->()
    46. {
    47. return m_pPtr;
    48. }
    49. int GetCount() {return *m_nConunt;}
    50. void AddRefCount()
    51. {
    52. m_xMutex->lock();
    53. ++(*m_nConunt);
    54. m_xMutex->unlock();
    55. }
    56. private:
    57. void Release()
    58. { // 更改计数时需要互斥信号量加锁
    59. bool deleteflag = false;
    60. m_xMutex->lock();
    61. if (--(*m_nConunt) == 0)
    62. {
    63. cout << *m_nConunt << endl;
    64. delete m_nConunt;
    65. delete m_pPtr;
    66. deleteflag = true;
    67. }
    68. m_xMutex->unlock();
    69. if (deleteflag == true)
    70. delete m_xMutex;
    71. }
    72. int* m_nConunt;
    73. T* m_pPtr;
    74. mutex* m_xMutex;
    75. };
    76. void TestSharePtr()
    77. {// 拷贝构造函数和直接赋值
    78. CSharePtr<int>* ptr1= new CSharePtr<int>(new int(1));
    79. CSharePtr<int> ptr2(*ptr1);
    80. CSharePtr<int> ptr3 = ptr2;
    81. cout << ptr1->GetCount() << endl;
    82. cout << ptr2.GetCount() << endl;
    83. cout << ptr3.GetCount() << endl;
    84. cout << "-------------------------" << endl;
    85. delete ptr1;
    86. }
    87. int main()
    88. {
    89. TestSharePtr();
    90. return 0;
    91. }