寫一個類,實現複雜對象的拷貝構造

//這是一個簡單的函數
class AnActor
{
public:

 AnActor(){ m_ptrString = NULL,m_ptrThread = NULL;}
 
 AnActor(AnActor &hsa)
 {
  m_ptrString = hsa.m_ptrString;
  m_ptrThread = hsa.m_ptrThread;

 }

private:

 CString *m_ptrString;
 CWindThread *m_ptrThread;


}

//這是一個複雜的函數

class UseCount{
public:

 UseCount():p(new int(1)){};
 UseCount(const UseCount& u):p(u.p){++*p;};
 UseCount& operator = (UseCount& h );
 ~UseCount(){ if(--*p==0) delete p; };
 bool Only(){return *p==1;}
 bool MakeOnly();
 bool Reattach(const UseCount& );

private:

 int* p;
 UseCount& oprator = (const UseCount &u);//沒寫函數體,可刪去不要
};

bool UseCount::Reattach(const UseCount& u)
{
 ++*u.p;
 if(--*p==0)
 {
  delete p;
  p = u.p;
  return true;
 }

 p = u.p;
 return false;
};

bool UseCount::MakeOnly()
{
 if(*p ==1) return false;
 
 --*p;
 p = new int(1);

 return true;
};

class Handle
{
public:

 Handle():m_ptrActor(new AnActor){};
 Handle(const Handle &hsa):m_Count(hsa.m_Count),m_ptrActor(hsa.m_ptrActor){};
 Handle(const AnActor &hsa):m_ptrActor(new AnActor(hsa)){};
 ~Handle(){if (m_Count.Only()) delete m_ptrActor;}
 Handle& operator = (const Handle hsa)
 {
  if(hsa.Reattach)(hsa.u)
  delete m_ptrActor;
  m_ptrActor = hsa.m_ptrActor;
  return *this;
 }

 AnActor* Actor() const {return m_ptrActor;};
 Handle& Actor(Handle& hsa)
 {
  if(hsa.MakeOnly())
  m_ptrActor = new AnActor(*m_ptrActor);
  return *this;
 }

 private:
 AnActor *m_ptrActor;
 UseCount m_Count;

};

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