1 #include <iostream> 2 class CBuff 3 { 4 public: 5 CBuff(const char* szBuff) 6 { 7 Init(); 8 SetBuff(szBuff); 9 } 10 void SetBuff(const char* szBuff) 11 { 12 ReduceCount(); 13 14 m_pBuff = new char[strlen(szBuff) + 1]; 15 m_pnCount = new int(1); 16 strcpy(m_pBuff, szBuff); 17 } 18 CBuff(const CBuff& buff) 19 { 20 m_pBuff = buff.m_pBuff; 21 m_pnCount = buff.m_pnCount; 22 (*m_pnCount)++; 23 } 24 ~CBuff() 25 { 26 ReduceCount(); 27 } 28 private: 29 void ReduceCount() 30 { 31 if (m_pBuff==nullptr) 32 { 33 return; 34 } 35 (*m_pnCount)--; 36 if (*m_pnCount==0) 37 { 38 delete[]m_pnCount; 39 delete[]m_pBuff; 40 m_pBuff = nullptr; 41 m_pnCount = nullptr; 42 } 43 } 44 void Init() 45 { 46 m_pBuff=nullptr; 47 m_pnCount = nullptr; 48 } 49 char* m_pBuff; 50 int* m_pnCount; 51 }; 52 53 54 int main() 55 { 56 57 CBuff buff1("hello"); 58 CBuff buff2 = buff1; 59 CBuff buff3 = buff2; 60 buff1.SetBuff("pp"); 61 62 return 0; 63 }
标签:nullptr,CBuff,pBuff,char,计数,szBuff,引用,pnCount From: https://www.cnblogs.com/yewu1/p/17157121.html