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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

丸子哥哥

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值