码迷,mamicode.com
首页 > 编程语言 > 详细

C++引用计数智能指针

时间:2015-06-20 09:12:08      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:引用计数   智能指针   

#include <iostream>
using namespace std;

template<typename Type>//引用计数的智能指针
class auto_ptr_
{
public:
    auto_ptr_(Type *t = NULL):ptr(t), count(1)
    {
    }
    auto_ptr_(const auto_ptr_<Type>& at) :ptr(at.ptr), count(at.count+1)
    {}
    auto_ptr_<Type>& operator=(const auto_ptr_<Type> &at)
    {
        if (this != &at)
        {
            if (ptr != NULL)
            {

                if (count == 1)
                    this->~auto_ptr_();//如果ptr已经存在且唯一指向目标。
                ptr = at.ptr;
                count = at.count + 1;
            }
        }
        return *this;
    }
    ~auto_ptr_()
    {
        if (count == 1)
        {
            if (ptr != NULL)
            {
                delete ptr;
                ptr = NULL;
            }
        }
    }
    Type* operator->()
    {
        return ptr;
    }
    Type& operator*()
    {
        return *this;
    }
private:
    Type *ptr;
    int count;
};
int main()
{
    int *a = new int(3);
    int *b = new int(4);
    auto_ptr_<int> ps(a);
    auto_ptr_<int> pb(ps);
    auto_ptr_<int> pc(b);
    pc=pb;
    auto_ptr_<int> pd(pc);
    return 0;
}

C++引用计数智能指针

标签:引用计数   智能指针   

原文地址:http://blog.csdn.net/liuhuiyan_2014/article/details/46566705

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!