计数指针,源码雏形

97 篇文章 0 订阅
92 篇文章 0 订阅

跟auto_ptr对照一下,auto_ptr复制或转移拥有权,看看计数指针有什么不同,看看计数指针是怎么实现的?

#include<iostream>
#include<string>
#include<deque>
#include<algorithm>
#include<vector>
#include<list>
using namespace std;
template<typename T>
class CountedPtr{
private:
	T* ptr;
	long *count;
public:
	explicit CountedPtr(T* p=0):ptr(p),count(new long(1)){}
	CountedPtr(const CountedPtr<T>& p)throw():ptr(p.ptr),count(p.count){
		++*count;
	}
	~CountedPtr()throw(){
		dispose();
	}
	CountedPtr<T>& operator=(const CountedPtr<T>& p)throw(){
		if(this!=&p){
			dispose();
			ptr=p.ptr;
			count=p.count;
			++*count;
		}
		return *this;
	}
	T& operator*()const throw(){
		return *ptr;
	}
	T* operator->()const throw(){
		return ptr;
	}
private:
	void dispose(){
		if(--*count==0){
			delete count;
			delete ptr;
		}
	}
};
void dayin(CountedPtr<int> elem){
	cout<<*elem<<" ";
}
int main(){
	static int values[]={3,5,9,1,6,4};
	typedef CountedPtr<int> InPtr;
	deque<InPtr>d;
	list<InPtr>l;

	for(int i=0;i<sizeof(values)/sizeof(*values);++i){
		InPtr ptr(new int(values[i]));
		d.push_back(ptr);
		l.push_front(ptr);
	}
	for_each(d.begin(),d.end(),dayin);
	cout<<endl;

	for_each(l.begin(),l.end(),dayin);
	cout<<endl;

	*d[2]*=*d[2];
	(**d.begin())*=-1;
	(**d.begin())=0;

	for_each(d.begin(),d.end(),dayin);
	cout<<endl;

	for_each(l.begin(),l.end(),dayin);
	cout<<endl;
	system("pause");
	return 0;
}


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值