设为首页 加入收藏

TOP

GNU,gcc,g++,gdb,cc概念(二)
2012-11-28 12:57:41 来源: 作者: 【 】 浏览:679
Tags:GNU gcc gdb 概念

 

    二、计数器的封装

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

    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为其它参数,与定义无关.

      

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇标准C++处理for循环作用域规则 下一篇C、C++异常处理区别

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: