首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

基于同伴类实现引用计数

2012-10-10 
基于伙伴类实现引用计数基于伙伴类实现引用计数实现原理图: 具体代码实现:/** This is class to implement

基于伙伴类实现引用计数

基于伙伴类实现引用计数

实现原理图:

基于同伴类实现引用计数

 

具体代码实现:

/** This is class to implement a reference counter* It is implement by the buddy class.*/#ifndef _BUDDYCLASS_H_#define _BUDDYCLASS_H_/*Here we just want to understand implement of the use of reference counter * So it only manager the int resource.* In the real world, it should be implement with the template which could be* used by other type resources.*///This is the buddy class to to manage the resource.class u_ptr{friend class HasPtr; //The  reference counter class(For the client)private:u_ptr(int *p):m_ptr(p),m_use(1){}~u_ptr(){ delete m_ptr; }private:int *m_ptr; //piont to the real resourceint m_use; //counting the reference time.};//The reference counter class(For the client)class HasPtr {public:HasPtr(int *p):m_pUptr(new u_ptr(p)){}~HasPtr(){ if(--(m_pUptr->m_use) == 0) delete m_pUptr; }HasPtr(const HasPtr& rOrg):m_pUptr(rOrg.m_pUptr) {++(m_pUptr->m_use); //copy constructor make the counter +1} HasPtr& operator=(const HasPtr& rh) //This has to situation (A = A or A = B){++(rh.m_pUptr->m_use);  //Both the situations should do this.if(--(m_pUptr->m_use) == 0){delete m_pUptr;}m_pUptr = rh.m_pUptr;return *this;}//over loading the operator * and operator -> to make the object looks like a pointer.int& operator*() const  //int is the real time of the resource we managed.{return *(m_pUptr->m_ptr);}int* operator->() const {return m_pUptr->m_ptr;}private:u_ptr *m_pUptr; //Point to the buddy class//add other resources here....};#endif


测试代码:

// ref_counter.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include "BuddyClass.h"#include <iostream>#include <vld.h> //visual memory detect.using namespace std;int _tmain(int argc, _TCHAR* argv[]){HasPtr ref_cnt(new int(42));HasPtr ref_cnt_2 = ref_cnt; //copy constructorref_cnt = ref_cnt; //A = A cout<<*ref_cnt<<endl; //42(*ref_cnt)++;cout<<*ref_cnt<<endl; //43cout<<*ref_cnt_2<<endl; //43HasPtr ref_cnt3(new int(28));ref_cnt = ref_cnt3;cout<<*ref_cnt<<endl; //28cout<<*ref_cnt_2<<endl; //43cout<<*ref_cnt3<<endl; //28return 0;}


运行结果:

基于同伴类实现引用计数

热点排行