引用计数

  当多个指针指向同一个对象,其中一个指针delete后,剩下的指针便成了野指针,浪费内存。
例如:

    int* a = new int(6);
    int *p = a;
    printf("p的地址为 :%x  值为: %d \n", p, *p);
    delete a;
    a = nullptr;
    printf("p的地址为 :%x  值为: %d \n", p, *p);
    return 0;

这里写图片描述

  在引用计数中,每一个对象负责维护对象所有引用的计数值。当一个新的引用指向对象时,引用计数器就递增,当去掉一个引用时,引用计数就递减。当引用计数到零时,该对象就将释放占有的资源。

  ,
  ,

代码实现:

class t_count {
private:
    int *_count;
public:
    t_count() :_count(new int(1)) {};
    t_count(t_count &tmp) {
        _count = tmp._count;
        ++*tmp._count;
    }
    void operator=(t_count &tmp) {
        if (--*_count == 0) {
            delete _count;
        }
        _count = tmp._count;
        ++*tmp._count;
    }
    bool isonly() {
        if (--*_count == 0)
            return true;
        else
            return false;
    }
    bool iscopy(t_count &tmp) {
        ++*tmp._count;
        if (--*_count == 0) {
            delete _count;
            _count = tmp._count;
            ++*tmp._count;
            return true;
        }
        _count = tmp._count;
        return false;
    }
    ~t_count() {
        if(--*_count==0){
            delete _count;
            _count == nullptr;
        }
    }
};

template<class T>
class smart_ptr {
private:
    T *_data;
    t_count *_c;
public:
    smart_ptr() :_data(new T), _c(new t_count) {};
    smart_ptr(T *tmp) :_data(tmp), _c(new t_count()) {};
    smart_ptr(const smart_ptr<T> &tmp) {
        _data = tmp._data;
        _c = new t_count(*tmp._c);
    }
    smart_ptr& operator=(smart_ptr<T> &tmp) {
        if (_c->iscopy(*tmp._c)) {
            delete _data;
        }
        _data = tmp._data;
        return *this;
    }
    T* get() {
        return *_data;
    }
    ~smart_ptr() {
        if (_c->isonly()) {
            cout << *_data<<" yes" << endl;
            delete _data;
            delete _c;
            _data = nullptr;
            _c = nullptr;
        }
        else {
            cout << *_data <<" no!" << endl;
        }
    }
};

int main()
{
    smart_ptr<int> a(new int(6));
    smart_ptr<int> b = a;
    smart_ptr<int> c = b;
    smart_ptr<int> d(new int(5));
    b = d;
    return 0;
}

  ,结果如下:
这里写图片描述

  
  输出的no,yes是在析构函数定义的,可以看出,当b=d后,执行return之后,调用d的析构函数,此时因为还有b和d共享一个对象,所以输出no,然后再执行c的析构函数,c此时是指向a的,所以输出6 no,之后调用b的析构、a的析构。
  从结果上来看,一个简单的智能指针,就做好啦~。

此次更新,是更新以前贴在这得代码不完整,以及没有一些分析。 —2018.6.14

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值