引用计数类

引用计数类头

#pragma once

class CImageInfoData
{
 friend class CImageInfo;
public:
 CImageInfoData(void);
 ~CImageInfoData(void);
 void operator = (CImageInfoData &info);
 CImageInfoData(CImageInfoData &info);
public:
 void set(void *image);
private:
 void newVal(void *image);
 void deleteVal();
private:
 void *image;
 unsigned refCount;
};


引用计数实现

#include "stdafx.h"
#include "ImageInfoData.h"

CImageInfoData::CImageInfoData(void)
{
 newVal(NULL);
 refCount = 0;
}

CImageInfoData::~CImageInfoData(void)
{
 deleteVal();
}

void CImageInfoData::operator = (CImageInfoData &info)
{
 deleteVal();
 newVal(info.image);
}

CImageInfoData::CImageInfoData(CImageInfoData &info)
{
 refCount = 0;
 newVal(info.image);
}

void CImageInfoData::newVal(void *image)
{
 this->image = image;
}

void CImageInfoData::deleteVal()
{
 if(image != NULL)
 {
  delete image;
 }
}

void CImageInfoData::set(void *image)
{
 deleteVal();
 newVal(image);
}
数据类头

#pragma once

#include "ImageInfoData.h"

class CImageInfo
{
public:
 CImageInfo(void);
 ~CImageInfo(void);
 void operator = (CImageInfo &info);
 CImageInfo(CImageInfo &info);
public:
 void set(void *image);
 void *Image();
private:
 void attachData(CImageInfoData *theData);
 void detachData();
public:
 BITMAPINFO header;
private:
 CImageInfoData *data;
};

数据类实现

#include "stdafx.h"
#include "ImageInfo.h"

CImageInfo::CImageInfo(void)
{
 attachData(NULL);
}

CImageInfo::~CImageInfo(void)
{
 detachData();
}

void CImageInfo::operator = (CImageInfo &info)
{
 detachData();
 attachData(info.data);
 memcpy(&header,&info.header,sizeof(BITMAPINFO));
}

CImageInfo::CImageInfo(CImageInfo &info)
{
 attachData(info.data);
 memcpy(&header,&info.header,sizeof(BITMAPINFO));
}

void CImageInfo::attachData(CImageInfoData *theData)
{
 if(theData == NULL)
 {
  //no data to attach to ,make new data
  data = new CImageInfoData;
 }else if(theData->refCount == UINT_MAX)
 {
  //avoid reference count overflow, make new data
  data = new CImageInfoData;
  set(theData->image);
 }else
 {
  //simply attach to data
  data = theData;
 }

 ++data->refCount;
}

void CImageInfo::detachData()
{
 if(--data->refCount == 0)
 {
  delete data;
  data = NULL;
 }
}

void CImageInfo::set(void *image)
{
 if(data->refCount > 1)
 {
  attachData(NULL);
 }

 data->set(image);
}

void *CImageInfo::Image()
{
 return data->image;
}


posted @ 2009-09-03 15:46  南守拥  阅读(267)  评论(0编辑  收藏  举报