1 template <typename T> 2 class CSmartPtr 3 { 4 public: 5 CSmartPtr(T* p = nullptr) 6 { 7 if (p != nullptr) 8 { 9 m_p = p; 10 m_pCnt = new int(1); 11 } 12 } 13 CSmartPtr(const CSmartPtr& ptr) 14 { 15 if (ptr.m_p == nullptr) 16 { 17 return; 18 } 19 m_p = ptr.m_p; 20 m_pCnt = ptr.m_pCnt; 21 ++(*m_pCnt); 22 } 23 ~CSmartPtr() 24 { 25 --(*m_pCnt); 26 if (*m_pCnt == 0) 27 { 28 delete m_p; 29 delete m_pCnt; 30 } 31 m_p = nullptr; 32 m_pCnt = nullptr; 33 } 34 CSmartPtr& operator=(const CSmartPtr& pT) 35 { 36 //1. 判断是不是自己 37 if (this == &pT) 38 { 39 return *this; 40 } 41 //2. 清理自身,减少引用计数 42 if (m_p != nullptr) 43 { 44 --(*m_pCnt); 45 if (*m_pCnt == 0) 46 { 47 delete m_p; 48 delete m_pCnt; 49 } 50 m_p = nullptr; 51 m_pCnt = nullptr; 52 } 53 //3. 拷贝目标,增加引用计数 54 m_p = pT.m_p; 55 m_pCnt = pT.m_pCnt; 56 if (pT.m_pCnt != nullptr) 57 { 58 ++(*m_pCnt); 59 } 60 61 return *this; 62 } 63 T* operator->() 64 { 65 return m_p; 66 } 67 T& operator*() 68 { 69 return *m_p; 70 } 71 //CFoo* Get(){return m_p;} 72 private: 73 T* m_p = nullptr; 74 int* m_pCnt = nullptr; 75 };
标签:CSmartPtr,return,pT,nullptr,智能,pCnt,ptr,指针 From: https://www.cnblogs.com/yewu1/p/17157129.html