您的位置:首页 > 编程语言 > C语言/C++

C++ 引用计数(reference count) 实现智能指针

2015-11-24 00:10 465 查看
前面说到,含有指针成员的类容易出现悬垂指针的问题,特别是类的对象有复制,赋值等行为时;

referecen count 的核心思维是,使用一个计数器来标识当前指针指向的对象被多少类的对象所使用,即记录指针指向对象被引用的次数;

构造函数中创建类的新对象时,初始化引用计数为1;

复制构造函数复制指针,并使相应的引用计数增加1;

赋值操作减少左操作数所值对象的引用计数,增加右操作数所指对象的引用计数;

析构函数使引用计数减少1,并且当引用计数为1时,释放指针说指向的对象;

使用引用计数实现智能指针的关键是,引用计数应该存在哪里

引用计数应该是某个类对象和其复制对象共享的, 而指针成员恰好有这样的特性, 故可以在类中多声明一个int * 的成员,用来表示引用计数

以下代码很好的解释了什么是引用计数:

//////////////////////////////////////////////////
/* */
//////////////////////////////////////////////////

#include <iostream>
#include <iterator>
#include <algorithm>
#include <fstream>
#include <list>
#include <string>
#include <vector>
#include <set>

class HasPtr
{
public:

//constructor
HasPtr(int *p,int i):ptr(p),val(i),pCount(new int) { *pCount = 1;}
//copy control
HasPtr(HasPtr & h):ptr(h.ptr),val(h.val),pCount(h.pCount) { ++(*pCount) ;}
HasPtr& operator=(HasPtr& );
~HasPtr();

void print_reference_count() { std::cout<<"shared object used times: "<<*pCount<<std::endl; }
int * get_prt() const {return ptr;}
int get_int() const { return val; }
void set_ptr(int *p) { ptr =p;}
void set_int(int i) {val = i;}
int get_ptr_val() const { return *ptr;}
void set_ptr_val(int val) { *ptr = val;}

private:
int * ptr;
int val;

//reference count members
int * pCount;
};

HasPtr& HasPtr::operator= (HasPtr& h)
{
ptr = h.ptr;
val = h.val;

++(*(h.pCount));
--(*pCount);

pCount = h.pCount;

return *this;

}

HasPtr::~HasPtr()
{
--(*pCount);

if(0 == (*pCount))
{
delete ptr;
delete pCount;
}
}

int main()
{
int* p = new int(42);
HasPtr test(p,50);
test.print_reference_count();
HasPtr test2(p,60);
test2.print_reference_count();

HasPtr test3(test);
test.print_reference_count();
test3.print_reference_count();

test2 = test3;
test.print_reference_count();
test3.print_reference_count();
test2.print_reference_count();

return 0;
}


int *pCount 是指向引用计数的指针;

实现引用计数还有其他的方式

//待补充
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: