使用shared_ptr 智能指针包含引用计数,管理方便。
代码如下:
#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;
}
运行结果:
h1(5:6):2
h2(3:4):1
h3(5:6):2
h4(7:8):2
h5(7:8):2
8 9
h1(5:6):1