C++ 沉思录 ——句柄——智能指针改写

  C++ 沉思录也算是C++中的经典书籍,其中介绍OO思想的我觉得很好,但是全书中贯穿了handle,使用引用计数等,也有点不适合现代C++的设计思想。这里使用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& x(int xv) 
    { 
        xval = xv; 
        return *this;
    };
    Point& y(int yv) 
    { 
        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){ /*++up->u;*/ };//此处复制的是handle,但是底层的point对象并未复制,只是引用计数加1
    Handle& operator=(const Handle& h)
    {
        up = h.up;
        return *this;
    };
    ~Handle()
    {
    };
    int x() const{return up->x();};
    Handle& x(int xv)
    {
        up->x(xv); 
        return *this;
    };

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

    Handle& y(int yv)
    {
        up->y(yv); 
        return *this;
    };
    int OutputU()
    {
        return up.use_count();
    }   //输出引用个数
private:
    shared_ptr<Point> up;
};

int main()
{
    //Point *p = new Point(8,9); 
    Point p(8,9);
    //Point p1 = p.x(88);
    //Point *pp = &p;
    Handle h1(1,2);
    Handle h2 = h1;        //此处调用的是构造函数Handle(const Handle& h)
    h2.x(3).y(4);               //此处的特殊写法是因为写xy函数内返回了对象
    Handle h3(5,6);        //此处调用Handle的赋值运算符重载函数Handle& operator=(const Handle& h)
    h1 = h3;
    Handle h4(p);
    Handle h5(h4);
    h4.x(7).y(8);
    //Handle h5(p1);
    //Handle h5 = h4;
    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;
    //delete pp; //不能这样,不是用new分配的空间
    //cout <<"h5(" << h5.x() <<":"<< h5.y() << "):" << h5.OutputU() <<endl;
    cout<<p.x()<<" "<<p.y()<<endl;
    //cout<<&p1<<endl;
    return 0;
}

运行结果:

C:\Windows\system32\cmd.exe /c handle_sharedptr.exe
h1(5:6):2
h2(3:4):1
h3(5:6):2
h4(7:8):2
h5(7:8):2
8 9
Hit any key to close this window...

可见这里的结果和“句柄”这里的完全一样。

posted @ 2012-08-10 21:11  KingsLanding  阅读(1652)  评论(0编辑  收藏  举报