一个C++中智能指针的设计(五)

2012-11-30 12:27:45 · 作者: · 浏览: 1171

 

    二、计数器的封装

    这个类很简单,有三个地方需要注意:

    1、类从模板类型继承,就是从T继承.上面的class window的话,就是RefCountedObject是window的派生类.

    2、封装计数器ref_count_.需要注意的是,对计数器的加减操作应该尽可能的保持原子性.

    3、计数器类提供多个构造函数,都是对传入的类型T的多种构造支持.

    template <class T>

    class RefCountedObject : public T {

    public:

    RefCountedObject() : ref_count_(0) {

    }

    template<typename P>

    explicit RefCountedObject(P p) : T(p), ref_count_(0) {

    }

    template<typename P1, typename P2>

    RefCountedObject(P1 p1, P2 p2) : T(p1, p2), ref_count_(0) {

    }

    template<typename P1, typename P2, typename P3>

    RefCountedObject(P1 p1, P2 p2, P3 p3) : T(p1, p2, p3), ref_count_(0) {

    }

    template<typename P1, typename P2, typename P3, typename P4>

    RefCountedObject(P1 p1, P2 p2, P3 p3, P4 p4)

    : T(p1, p2, p3, p4), ref_count_(0) {

    }

    template<typename P1, typename P2, typename P3, typename P4, typename P5>

    RefCountedObject(P1 p1, P2 p2, P3 p3, P4 p4, P5 p5)

    : T(p1, p2, p3, p4, p5), ref_count_(0) {

    }

    virtual ~RefCountedObject() {

    }

    virtual int AddRef() {

    return Increment(&ref_count_);

    }

    virtual int Release() {

    int count = Decrement(&ref_count_);

    if (!count) {

    delete this;

    }

    return count;

    }

    protected:

    int ref_count_;

    };

    三、实例

    scoped_refptr<Window> win(new RefCountedObject<Window>(&client, &wnd));

    上面的实例定义了一个智能指针win,式中client和wnd为其它参数,与定义无关.