C++引用计数

引用计数:

        当多个对象同时使用一个相同对象的资源时,会发生两种情况:       

浅拷贝时,虽然节约资源,但是释放的时候会出现问题。
深拷贝时,虽然释放不会出现问题,但是浪费了资源。
为了两者都兼容,出现了引用计数。

#include "stdafx.h"
#include "Student.h"

int main(int argc, char* argv[])
{

  CStudent stu1("小明");

  CStudent stu2 = stu1;
  CStudent stu3 = stu1;
  CStudent stu4 = stu1;
  CStudent stu5 = stu1;

  stu5.SetName("小芳");

  stu3 = stu3;

  CStudent stu6 = stu5;

	return 0;
}
#include "stdafx.h"
#include "Student.h"
#include <STRING.H>

CRefCount::CRefCount(char* pszName)
{
  SetName(pszName);
}

CRefCount::~CRefCount()
{
  if (m_szName == NULL)
  {
    delete m_szName;
    m_szName = NULL;
  }
}

bool CRefCount::SetName(char* pszName)
{
  m_szName = new char[256];
  
  strcpy(m_szName, pszName);
  m_nRefCount = 1;

  return true;
}

bool CRefCount::AddRef()
{
  m_nRefCount++;

  return true;
}

bool CRefCount::ReleaseRef()
{
  if (--m_nRefCount == 0)
  {
    delete this; 
  }

  return true;
}

CStudent::CStudent()
{
  m_pRef = NULL;
}

CStudent::CStudent(char* pszName)
{
  m_pRef = new CRefCount(pszName);
}

void CStudent::SetName(char* pszName)
{
  if (m_pRef != NULL)
  {
     m_pRef->ReleaseRef();
  }

    m_pRef = new CRefCount(pszName);
}

CStudent::~CStudent()
{
  if (m_pRef != NULL)
  {
    m_pRef->ReleaseRef();
    m_pRef = NULL;
  }
}

CStudent::CStudent(CStudent& obj)
{
  m_pRef = NULL;
  if (obj.m_pRef != NULL)
  {  
    m_pRef = obj.m_pRef;
    m_pRef->AddRef();
  }
}

CStudent& CStudent::operator=(const CStudent& oj)
{
  if (m_pRef == oj.m_pRef)
  {
    return *this;
  }

  if (m_pRef != NULL)
  {
    m_pRef->ReleaseRef();
  }

  m_pRef = oj.m_pRef;
  m_pRef->AddRef();

  return *this;
}


猜你喜欢

转载自blog.csdn.net/qq_36818386/article/details/80243673