智能指针

闲着没事写了个智能指针

#include <iostream>


class SmartCount {
  public:
    explicit SmartCount(int count) : count_(0) {
      count_ = count;
    }
  private:
    explicit SmartCount(const SmartCount&);
    SmartCount& operator = (const SmartCount&);
  public:
    int AddCount() {return ++count_;}
    int Release() {return --count_;}
  private:
    int count_;

};

template<class T>
class SmartPtr {
  public:
    SmartPtr(T* ptr):ptr_(ptr),counter_(new SmartCount(1)) {
      
    }

    ~SmartPtr() {
      if (ptr_ && counter_->Release() <= 0) {
        delete ptr_;
        ptr_ = NULL;
        delete counter_;
        counter_ = NULL;
      }
    }

  public:
    SmartPtr(const SmartPtr<T>& smart_ptr) {
      ptr_ = smart_ptr.ptr_;
      counter_ = smart_ptr.counter_;
      if (counter_) {
        counter_->AddCount();
      }
    } 


    SmartPtr& operator = (const SmartPtr<T>& smart_ptr) {
      if (&smart_ptr == this) {
        return *this;
      }
      if (smart_ptr.counter_) {
        smart_ptr.counter_->AddCount();
      }
      T* ptr_temp = ptr_;
      SmartCount* count_temp = counter_;
      ptr_ = smart_ptr.ptr_;
      counter_ = smart_ptr.counter_;
      if (ptr_temp && count_temp->Release() <= 0) {
        delete ptr_temp;
        ptr_temp = NULL;
        delete count_temp;
        count_temp = NULL;
      }
      return *this;
    }

    T* operator -> (void) {
      return ptr_;
    }

    T& operator * (void) {
      return *ptr_;
    }

    


  private:
    T* ptr_;
    SmartCount* counter_;
};

#include "main.h"

using namespace std;

class Test {
  public:
    Test(char* ch) {ch_ = ch;}
    ~Test() { }

    void Print() {
      cout << ch_ << endl;
      cout << "333333" << endl;
    }
  private:
    char* ch_;

};

int main(int argc, char* argv[]) {
 SmartPtr<Test> p ( new Test("123"));
 p->Print();

 SmartPtr<Test> p2(new Test("333"));
 p2 = p;
 p2->Print();

 SmartPtr<Test> p3(p2);
 p3->Print();
}


骑虎100 一个有趣的网站 好玩的网站 http://www.qihu100.com


转载于:https://my.oschina.net/hejiula/blog/272439

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值