简单的计数智能指针实现

template<class T>
class myCountPtr{
     public:
       T *p_re;
       int *count;
     public:
       explicit myCountPtr(T *p=0):p_re(p),count(new int(1)){ }
       
       myCountPtr( const myCountPtr<T>& rhs):p_re(rhs.getRe()),count(rhs.getCount())
       { 
        
         ++(*count);
       }
       T* getRe()const{return p_re;} 
        
       myCountPtr<T>& operator=(const myCountPtr<T>& rhs)
       {
           if(this!=&rhs)
            {
              depose();
              p_re=rhs.getRe();
              count=rhs.count;
              ++(*count);
            }
         return *this;
       }
       T & operator*(){return *p_re;}
       T*  operator->(){return p_re;}
       ~myCountPtr()
       {
         depose();
       }
       int *getCount(){return count;}
       void depose()
       {
         if(--(*count)==0)
          {
            delete count;
            delete p_re;
          }
        }
};

int main()
{
   myCountPtr<string> p1(new string("hello"));
 
   cout<<*p1<<" "<<*(p1.getCount())<<endl;
   myCountPtr<string> p2;
   p2=p1;
   cout<<*p2<<" "<<*(p2.getCount())<<endl;
   cout<<*p1<<" "<<*(p1.getCount())<<endl;
}

智能指针是一种用于自动管理动态分配内存的工具。其中最常见的智能指针C++中的std::shared_ptr和std::unique_ptr。下面是一个简单实现智能指针的示例: ```c++ #include <iostream> template <typename T> class SmartPointer { public: SmartPointer(T* ptr) : ptr_(ptr), ref_count_(new size_t(1)) { } SmartPointer(const SmartPointer<T>& other) : ptr_(other.ptr_), ref_count_(other.ref_count_) { ++(*ref_count_); } ~SmartPointer() { if (--(*ref_count_) == 0) { delete ptr_; delete ref_count_; } } SmartPointer<T>& operator=(const SmartPointer<T>& other) { if (this != &other) { if (--(*ref_count_) == 0) { delete ptr_; delete ref_count_; } ptr_ = other.ptr_; ref_count_ = other.ref_count_; ++(*ref_count_); } return *this; } T& operator*() const { return *ptr_; } T* operator->() const { return ptr_; } private: T* ptr_; size_t* ref_count_; }; int main() { SmartPointer<int> sp1(new int(5)); std::cout << *sp1 << std::endl; SmartPointer<int> sp2 = sp1; std::cout << *sp2 << std::endl; sp1 = SmartPointer<int>(new int(10)); std::cout << *sp1 << std::endl; std::cout << *sp2 << std::endl; return 0; } ``` 在上面的例子中,我们定义了一个模板类 SmartPointer,它保存了一个指向动态分配内存的原始指针 ptr_,以及一个引用计数 ref_count_。构造函数中,我们将引用计数初始化为1。当拷贝构造一个智能指针时,我们增加引用计数。当析构一个智能指针时,我们减少引用计数,并在引用计数变为0时释放内存。赋值运算符重载中,我们首先减少旧指针的引用计数,然后增加新指针的引用计数。 这只是一个简单智能指针实现示例,实际上,标准库中的std::shared_ptr和std::unique_ptr提供了更多的功能和安全性保证。但是这个实现可以帮助你理解智能指针的基本原理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值