zoukankan      html  css  js  c++  java
  • 智能指针实现

    下面是一个智能指针的实现,很好,可以多多采用。


    #ifndef SMART_PTR_H
    #define SMART_PTR_H

    //智能指针,可以加入set或map,利用其排序参数进行排序
    //set或map调用clear或erase会调用SmartPtr析构函数,不再被引用的数据指针会被delete

    template <class T>
    class SmartPtr
     {
         private:
       T* ptr;        // pointer to the value  指针
       long* count;   // shared number of owners  计数
         public:
       //initialize pointer with existing pointer
       //-requires that the pointer p is a return value of new
      
       //构造函数  用explicit修饰,不允许隐形转换
       explicit SmartPtr (T* p=0)
        : ptr(p), count(new long(1))
       {
       }

       //copy pointer (one more owner)  复制构造函数
       SmartPtr (const SmartPtr<T>& p) throw()
        : ptr(p.ptr), count(p.count)
       {
        ++*count;
       }

       //destructor (delete value if this was the last owner)析构函数
       ~SmartPtr () throw()
       {
        dispose();
       }

       //assignment (unshare old and share new value)  重载assignment 运算符
       SmartPtr<T>& operator= (const SmartPtr<T>& p) throw()
       {
        if (this != &p)
        {
         dispose();
         ptr = p.ptr;
         count = p.count;
         ++*count;
        }
        return *this;
       }

       //access the value to which the pointer refers 重载* 运算符
       T& operator*() const throw()
       {
        return *get();
       }

       T* operator->() const throw()
       {
        return get();
       }

       T* get() const throw()
       {
        return  ptr;
       }
       

         private: 
       //销毁
       void dispose()
       {
        if (--*count == 0) {
         delete count;
         delete ptr;
        }
       }
    };


    #endif

  • 相关阅读:
    Nginx IP限制
    Hadoop 基本原理
    Redis 主从复制原理
    ThreadLoacl 小记
    Spring boot @Transaction,@Async在同一个类中注解失效的原因和解决办法
    Kafka学习
    Spring BeanUtils简单使用
    精彩的解释CAP理论的文章
    tcp粘包,udp丢包
    java多线程
  • 原文地址:https://www.cnblogs.com/skyofbitbit/p/2677407.html
Copyright © 2011-2022 走看看