写一个类,实现复杂对象的拷贝构造

来源:互联网 发布:怎么用淘宝链接卖东西 编辑:程序博客网 时间:2024/06/05 23:19

//这是一个简单的函数
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;

};

原创粉丝点击