0%
线程安全的share指针
1. 代码部分
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
| #include <iostream> #include <mutex> using namespace std;
class Counter{ public: Counter(): m_Counter(0) {} Counter(const Counter&) = delete; Counter& operator=(const Counter&) = delete; ~Counter() {} void reset() { m_Counter = 0; } unsigned int get() const { return m_Counter; } void operator++() { m_Counter++; } void operator++(int) { m_Counter++; } void operator--() { m_Counter--; } void operator--(int) { m_Counter--; }
private: unsigned int m_Counter{}; };
template<typename T> class SharedPtr{ public: explicit SharedPtr(T *ptr = nullptr): // explicit pData(ptr), pCounter(new Counter()), pMutex(new std::mutex) { if (ptr) { addCount(); } }
SharedPtr(const SharedPtr<T>& sp) { pData = sp.pData; pCounter = sp.pCounter; pMutex = sp.pMutex; addCount(); }
SharedPtr<T>& operator=(const SharedPtr<T>& sp) { if (pData != sp.pData) { subCount(); pData = sp.pData; pCounter = sp.pCounter; pMutex = sp.pMutex; addCount(); } }
T* operator->() { return pData; }
T& operator*() { return *pData; }
T* get() { return pData; }
unsigned int getCount() { return pCounter->get(); }
~SharedPtr() { subCount(); }
private: void addCount() { pMutex->lock(); ++(*pCounter); pMutex->unlock(); }
void subCount() { bool deleteflag = false; pMutex->lock(); --(*pCounter); if (pCounter->get() == 0) { delete pCounter; delete pData; deleteflag = true; } pMutex->unlock(); if (deleteflag == true) delete pMutex; }
private: T *pData; std::mutex *pMutex; Counter *pCounter; };
class MyClass { public: MyClass() { cout << "Constructor" << endl; } ~MyClass() { cout << "Destructor" << endl; } };
int main() { SharedPtr<MyClass> p(new MyClass()); SharedPtr<MyClass> p2 = p; cout << "END" << endl; return 0; }
|
2. 参考资料