c++的引用计数与写时复制

来源:互联网 发布:拉伸法测杨氏模量数据 编辑:程序博客网 时间:2024/05/01 03:41

最近看了C++沉思录,了解一下句柄类,其中的引用计数,写时复制技术很值得学习,特将它摘抄下来,希望它对大家也有用。
//原始类
class CPoint
{
public:
    CPoint(): xval(0), yval(0)
    {}
    CPoint(int x, int y): xval(x), yval(y)
    {}
    int x() const
    {
        return xval;
    }
    int y() const
    {
        return yval;
    }
    CPoint& x(int xv)
    {
        xval = xv;
        return *this;
    }
    CPoint& y(int yv)
    {
        yval = yv;
        return *this;
    }
private:
    int xval;
    int yval;
};
//引用计数类
class UseCount
{
public:
    UseCount();
    UseCount(const UseCount&);
    bool reattach(const UseCount&);
    ~UseCount();
    bool only();
    bool makeOnly();
    int getCount();
private:
    //禁止赋值
    UseCount& operator=(const UseCount&);
    int* p;
};
UseCount::UseCount(): p(new int(1))
{}
UseCount::UseCount(const UseCount& u): p(u.p)
{
    ++*p;
}
//返回值为true 需要删除宿主类的赋值
bool UseCount::reattach(const UseCount& u)
{
    ++*u.p;
    if (--*p == 0)
    {
        delete p;
        p = u.p;
        return true;
    }
    p = u.p;
    return false;
}
//写时复制
bool UseCount::makeOnly()
{
    if (*p == 1)
    {
        return false;
    }
    --*p;
    p = new int(1);
    return true;
}
int UseCount::getCount()
{
    return *p;
}
UseCount::~UseCount()
{
    if (--*p == 0)
    {
        delete p;
    }
}
//确保只有一个引用
bool UseCount::only()
{
    return *p == 1;
}
//句柄类
class Handle
{
public:
    Handle();
    Handle(int, int);
    Handle(const CPoint& p0);
    Handle(const Handle&);
    Handle& operator=(const Handle&);
    ~Handle();
    int x() const;
    Handle& x(int);
    int y() const;
    Handle& y(int);
    int getCount();
private:
     CPoint* p;
     UseCount u;
};
Handle::Handle(): p(new CPoint)
{

}
Handle::Handle(int x, int y): p(new CPoint(x, y))
{

}
Handle::Handle(const CPoint& p0): p(new CPoint(p0))
{

}
Handle::Handle(const Handle& h): u(h.u), p(h.p)
{

}
Handle& Handle::operator=(const Handle& h)
{
    if (u.reattach(h.u))
    {
        delete p;
    }
    p = h.p;
    return *this;
}
Handle::~Handle()
{
    if (u.only())
    {
        delete p;
    }
}
int Handle::getCount()
{
    return u.getCount();
}
int Handle::x() const
{
    return p->x();
}
Handle& Handle::x(int x0)
{
    if (u.makeOnly())
    {
        p = new Point(*p);
    }
    p->x(x0);
    return *this;
}

原创粉丝点击