C++中的智能指针

来源:互联网 发布:淘宝套现被买家退款 编辑:程序博客网 时间:2024/05/16 18:56

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


//T1class cp{private:friend class sp;cp(int *px):p(px),count(1){}int *p;int count;~cp() {delete p;}};//T2class 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;elsereturn 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:第一次写博客。。有错的地方大家轻喷。。。= =。。

原创粉丝点击