內存空間釋放問題

////////////////////////////////////////////////////////////////////避免內存泄漏
class SimplyClass{
private:
 char *m_buf;
 size_t m_nSize;
 int m_count;
public:
 SimplyClass(size_t n=1):m_nSize(n),m_buf(new char[n]),m_count(1){printf("count id %d/n",m_count);};
 ~SimplyClass(){
  (m_count)--;//爲0才釋放內存
  printf("count is %d/n",m_count);
  if(m_count==0)
  {
   printf("%d is deleted at %xd/n",m_nSize,m_buf);
   delete [] m_buf;
   m_buf=NULL;
  }
 }
 char*GetBuffer()const{return m_buf;}
 //拷貝函數的實現~~用了引用計數的辦法~`解決多次釋放同一內存地址空間的問題
 SimplyClass(const SimplyClass&a){
  m_nSize=a.m_nSize;
  m_buf=a.m_buf;
  m_count=a.m_count;
  (m_count)++;
  printf("count is %d/n",m_count);
 }
 SimplyClass& operator=(const SimplyClass&s){
  if(m_buf==s.m_buf)
   return *this;
  (m_count)--;

  if(m_count==0)
  {
   printf("%d is deleted at %xd/n",m_nSize,m_buf);
   delete[] m_buf;
   m_buf=NULL;
   m_count=1;
  }
  m_buf=s.m_buf;
  m_nSize=s.m_nSize;
  m_count=s.m_count;
  (m_count)++;
 }


};

void foo(){
 SimplyClass a(10);
 
 SimplyClass b=a;
 //這樣就會造成a內存地址~~兩次被釋放而出錯
 //可用將拷貝函數寫爲private類型~~但編譯時會報錯
 //最好是引用計數來解決~~但是如果再加上下面這一句~~又有問題

 SimplyClass c(20);
 c=a;//c本來又20個字節的內存~~~但是最後沒釋放~~解決辦法~~重載'='運算符
 
 char*pChar1=a.GetBuffer();
 
 strcpy_s(pChar1,sizeof("Hello!"),"Hello!");

 printf("%s,/n",pChar1);
}
void main(void){
 foo();
 return;
 
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章