IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    使用C++实现一简单智能指针类

    armsword发表于 2014-11-22 15:05:16
    love 0

    智能指针类与普通指针一样,但它借由自动化内存管理保证了安全性,避免了诸如悬挂指针、内存泄露和分配失败等问题。智能指针有好几种实现方式,STL和Boost库里都有实现,比如使用句柄类和引用计数方式。我们现在使用引用计数定义智能指针,智能指针类将一个计数器与类指向的对象相关联。使用计数跟踪该类有多少个对象共享同一指针。使用计数为0时,删除对象。使用计数有时也称为引用计数(reference count)。

    使用一个计数变量,并将其置一,每新增一个对象的引用,该变量会加一,移除一个引用则减一,即当对象作为另一对象的副本而创建时,复制构造函数复制指针并增加与之相应的使用计数的值。当对一个对象进行赋值时(=操作符),覆写=操作符,这样才能将一个旧的智能指针覆值给另一指针,旧的引用计数减一,新的智能指针的引用计数则加一。

    示例如下:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    template
    class SmartPointer
    {
    public:
    SmartPointer(T* ptr)
    {
    ref = ptr;
    ref_count = (unsigned*)malloc(sizeof(unsigned));
    *ref_count = 1;
    }
    SmartPointer(SmartPointer& sptr)
    {
    ref = sptr.ref;
    ref_count = sptr.ref_count;
    ++(*ref_count);
    }
    /* 覆写=运算符,这样才能将一个旧的智能指针赋值给另一指针,
    * 旧的引用计数减一,新的智能指针的引用计数则加一。
    */
    SmartPointer& operator=(SmartPointer& sptr)
    {
    if(this == &sptr;)
    {
    return *this;
    }
    // 若已赋值为某个对象,则移除引用
    if(*ref_count > 0)
    {
    remove();
    }
    ref = sptr.ref;
    ref_count = sptr.ref_count;
    ++(*ref_count);
    return *this;
    }
    ~SmartPointer()
    {
    remove(); // 移除一个对象引用
    }
    T getValue()
    {
    return *ref;
    }
    protected:
    void remove()
    {
    --(*ref_count);
    if(*ref_count == 0)
    {
    delete ref;
    free(ref_count);
    ref = NULL;
    ref_count = NULL;
    }
    }
    T* ref;
    unsigned* ref_count;
    };

    参考资料:
    《C++ Primer》
    《Crack The Interview》



沪ICP备19023445号-2号
友情链接