share_ptr 实现c++ 句柄引用计数

智能指针在超出生命范围时会自动被回收,在被引用时(或者赋值)会增加计数。所以在重载的构造函数、拷贝构造函数和赋值函数里来使用智能指针计算引用计数。

代码如下

#include <iostream>
#include <memory>
using namespace std;


class Point{
public:
Point() : xval(0),yval(0){};
Point(int x, int y): xval(x), yval(y){};
Point(const Point & p)
{
if(this == &p)
return ;
this->xval = p.x();
this->yval = p.y();
}
int x() const {return xval;};
int y() const {return yval;};
Point& setXY(int xv,int yv) 
{ 
xval = xv; 
yval = yv;
return *this;
};
private:
int xval, yval;
};


class Handle{                       //句柄类
public:
Handle(): up(new Point){};
Handle(int x,int y): up(new Point(x,y)){};//按创建Point的方式构造handle,handle->UPoint->Point
Handle(const Point& p): up(new Point(p)){};//创建Point的副本
Handle(const Handle& h): up(h.up){};//此处复制的是handle,但是底层的point对象并未复制,只是引用计数加1
Handle& operator=(const Handle& h)
{
up = h.up;
return *this;
};
~Handle()
{
};
Handle& setXY(int xv,int yv)
{
up->setXY(xv,yv); 
return *this;
};


int y() const{return up->y();}
int x() const{return up->x();}


int OutputU()
{
return up.use_count();
}   //输出引用个数
private:
shared_ptr<Point> up;
};


int main()
{
Handle h1(1,2);
{
Point p(8,9);

Handle h2 = h1;        //此处调用的是构造函数Handle(const Handle& h)
h2.setXY(3,4);              
Handle h3(5,6);        
h1 = h3;
Handle h4(p);
Handle h5(h4);
h4.setXY(7,8);
cout <<"h1(" << h1.x() <<":"<< h1.y() << "):" << h1.OutputU() <<endl;
cout <<"h2(" << h2.x() <<":"<< h2.y() << "):" << h2.OutputU() <<endl;
cout <<"h3(" << h3.x() <<":"<< h3.y() << "):" << h3.OutputU() <<endl;
cout <<"h4(" << h4.x() <<":"<< h4.y() << "):" << h4.OutputU() <<endl;
cout <<"h5(" << h5.x() <<":"<< h5.y() << "):" << h5.OutputU() <<endl;
cout<<p.x()<<" "<<p.y()<<endl;
}
cout <<"h1(" << h1.x() <<":"<< h1.y() << "):" << h1.OutputU() <<endl;
return 0;
}



输出如下


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值