/*! @share_ptr.cpp
* 实现share_ptr智能指针
* wang_haolin
* 2022/7/5
*/
#include<iostream>
#include<mutex>
using namespace std;
template<class T>
class CSharePtr
{
public:
CSharePtr(T* ptr = nullptr) :
m_pPtr(ptr),
m_nConunt(new int(1)),
m_xMutex(new mutex)
{}
~CSharePtr()
{
Release();
}
CSharePtr(const CSharePtr<T>& sp)
{
m_pPtr = sp.m_pPtr;
m_nConunt = sp.m_nConunt;
m_xMutex = sp.m_xMutex;
AddRefCount();
}
CSharePtr<T>& operator=(const CSharePtr<T> sp)
{ // 赋值引用计数+1
if (sp.m_pPtr != m_pPtr)
{ // 释放旧有资源
Release();
m_pPtr = sp.m_pPtr;
m_nConunt = sp.m_nConunt;
m_xMutex = sp.m_xMutex;
AddRefCount();
}
return *this;
}
T& operator*()
{
return *m_pPtr;
}
T* operator->()
{
return m_pPtr;
}
int GetCount() {return *m_nConunt;}
void AddRefCount()
{
m_xMutex->lock();
++(*m_nConunt);
m_xMutex->unlock();
}
private:
void Release()
{ // 更改计数时需要互斥信号量加锁
bool deleteflag = false;
m_xMutex->lock();
if (--(*m_nConunt) == 0)
{
cout << *m_nConunt << endl;
delete m_nConunt;
delete m_pPtr;
deleteflag = true;
}
m_xMutex->unlock();
if (deleteflag == true)
delete m_xMutex;
}
int* m_nConunt;
T* m_pPtr;
mutex* m_xMutex;
};
void TestSharePtr()
{// 拷贝构造函数和直接赋值
CSharePtr<int>* ptr1= new CSharePtr<int>(new int(1));
CSharePtr<int> ptr2(*ptr1);
CSharePtr<int> ptr3 = ptr2;
cout << ptr1->GetCount() << endl;
cout << ptr2.GetCount() << endl;
cout << ptr3.GetCount() << endl;
cout << "-------------------------" << endl;
delete ptr1;
}
int main()
{
TestSharePtr();
return 0;
}