C++中的智能指针

本文介绍了一种基于C++的简单智能指针实现方法,通过两个类T1和T2来实现计数引用和自动内存管理。T1类负责管理原始指针和引用计数,而T2类则持有指向T1的指针,实现了引用计数的增加和减少,当引用计数归零时释放内存。

学习了C++primer第四版中的智能指针后趁热写的。。。不知道有没有写错
思路
总的思路就是有2个类。T1,T2,


//T1
class cp
{
private:
	friend class sp;
	cp(int *px):p(px),count(1){}
	int *p;
	int count;
	~cp() {delete p;}
};
//T2
class sp
{
public:
	sp(sp &p):ptr(p.ptr){++ptr->count ;}
	sp(int *p,int i):ptr(new cp(p)){*(ptr->p)=i;}
	bool is_thesame(sp &k);
	sp &operator=(sp &n);
	int &operator*();
	~sp() {if(0==(--ptr->count)) delete ptr;}
private:
	cp *ptr;
};




其中一个存放指针和计数(T1),另一个类(T2)中有一个指针指向第一个类。
当有一个T2指向T1时,T1中的计数+1,当T2由指向T1指向另一个T1时,原T1中的计数-1
当计数为0时,删除存放数据的那块内存。。。


代码


#include <string>
#include <iostream>
using namespace std;
class cp
{
private:
	friend class sp;
	cp(int *px):p(px),count(1){cout<< "Cp Created!"<<endl;}
	int *p;
	int count;
	~cp() {cout<< "Cp Destroyed!"<<endl;delete p;}
};
class sp
{
public:
	sp(sp &p):ptr(p.ptr){++ptr->count ;cout<<"(add)used :"<<ptr->count <<endl;}
	sp(int *p,int i):ptr(new cp(p)){*(ptr->p)=i;cout<<"(add)used :"<<ptr->count <<endl;}
	bool is_thesame(sp &k);
	sp &operator=(sp &n);
	int &operator*();
	~sp() {cout<<"(after delete)used :"<<ptr->count-1 <<endl;if(0==(--ptr->count)) delete ptr;}
private:
	cp *ptr;
};
bool sp::is_thesame(sp &k) 
{
	if(k.ptr==this->ptr)      
		return 1;
	else
		return 0;
}
sp &sp::operator=(sp &n)
{
	if(n.is_thesame(*this)) return *this;     //当相等时,直接返回

	--ptr->count;				//不相等时,自己看一下啦
	++n.ptr->count ;
	if(ptr->count ==0) delete ptr;           //计数为0时,删除指针
	if(n.ptr->count==0) delete n.ptr;
	ptr=n.ptr;
	return *this;
}
int &sp::operator*()
{
	return *(this->ptr->p);
}
void test()
{
	sp b(new int,10);
	sp a=b;
	sp d(new int,11);
	cout<< *d<<endl;
	d=a;
	cout<<*a<<endl;
}
int main()
{
	test();
}


运行截图



PS:第一次写博客。。有错的地方大家轻喷。。。= =。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值