zoukankan      html  css  js  c++  java
  • 创建数据结构库基础设施——智能指针类

    1,数据结构库架构图(本文暂时架构图,后有更改):

     

    2,内存泄漏(臭名昭著 bug):

           1,动态申请堆空间,用完后不归还;

                  1,短空间没影响,长时间会使堆空间内存变少;

                  2,对服务器来说很麻烦,因为服务器很久不重启;

           2,C++ 语言中没有垃圾回收的机制;

                  1,Java、C#、Python 语言中有,申请了堆空间没用就归还;

           3,指针无法控制所指堆空间的生命周期;

          

    3,当代 C++ 中的智能指针:

           1,指针生命周期结束时主动释放堆空间;

           2,一片堆空间最多只能由一个指针标识;

           3,杜绝指针运算和指针比较;

          

    4,智能指针设计方案:

           1,通过类模板描述指针的行为:    

                  1,能够定义不同类型的指针对象;

           2,重载指针特征操作符(-> 和 *):

                  1,利用对象模拟原生指针行为;

                  2,利用对象的析构函数主动释放堆空间;

    5,智能指针编程实验:

     1 #ifndef SMARTPOINTER_H
     2 #define SMARTPOINTER_H
     3 
     4 namespace DTLib
     5 {
     6 
     7 template <typename T>
     8 class SmartPointer : public Pointer<T>
     9 {
    10 public:
    11    SmartPointer(T* p = NULL) : Pointer<T>(p)
    12    {
    13    }
    14 
    15    SmartPointer(const SmartPointer<T>& obj)  // 这里为了一片堆空间只能由一个指针标识;
    16    {
    17        this->m_pointer = obj.m_pointer;
    18        const_cast<SmartPointer<T>&>(obj).m_pointer = NULL;  // 去除常量属性、然后置空;
    19    }
    20 
    21    SmartPointer<T>& operator= (const SmartPointer<T>& obj)
    22    {
    23        if( this != &obj)
    24        {
    25            T* p = this->m_pointer;  // 改成异常安全的,之前这里是delete m_pointer;
    26            this->m_pointer = obj.m_pointer;
    27            const_cast<SmartPointer<T>&>(obj).m_pointer = NULL;
    28            delete p;
    29        }
    30        return *this;
    31    }
    32 
    33     T* operator-> ()       
    34     {
    35         return m_pointer;
    36     }
    37 
    38     T& operator* ()
    39     {
    40         return *m_pointer;
    41     }
    42 
    43     bool isNull() 
    44     {
    45         return ( m_pointer == NULL );
    46     }
    47 
    48     T* get() 
    49     {
    50         return m_pointer;
    51     }
    52 
    53    ~SmartPointer()  // 必须要,否则这里是纯虚类;
    54    {
    55        delete this->m_pointer;
    56    }
    57 };
    58 
    59 }
    60 #endif // SMARTPOINTER_H

                 

    6,智能指针设计准则:

           1,指针生命周期结束时主动释放堆空间;

           2,一片堆空间最多只能由一个指针标识;

           3,杜绝指针运算和指针比较;

          

    7,智能指针使用军规:      

           1,只能用来指向堆空间中的单个对象或者单个变量,且不能用来指向堆空间中的数组;

           2,不能指向局部的对象或者局部的变量;

  • 相关阅读:
    CodeForces 734F Anton and School
    CodeForces 733F Drivers Dissatisfaction
    CodeForces 733C Epidemic in Monstropolis
    ZOJ 3498 Javabeans
    ZOJ 3497 Mistwald
    ZOJ 3495 Lego Bricks
    CodeForces 732F Tourist Reform
    CodeForces 732E Sockets
    CodeForces 731E Funny Game
    CodeForces 731D 80-th Level Archeology
  • 原文地址:https://www.cnblogs.com/dishengAndziyu/p/10920501.html
Copyright © 2011-2022 走看看