Smart pointer

Time:2020-11-3

Why is there a smart pointer

For C / C + + programs, there is always a mystery, that is, memory leakage. This project must use pointers. In order to facilitate the subsequent development of the program, first establish a class of intelligent pointer. This category should meet the following requirements:

    1. At the end of the pointer’s life cycle, the memory pointed to by the pointer is also released
    1. A space can only be represented by one pointer
    1. Eliminate pointer operation

2 design scheme

  • Make use of the function of C + + language to make a class of C + +. At the end of the pointer class’s life, space is released in the destructor.
  • 2 use object to simulate the behavior of native pointer. For example, overloaded pointer feature operators’ – > ‘and

3 code implementation

Contents of category 3.1

  1. Overload the ‘*’ and ‘- >’ operators to realize the basic operation function of pointer.

    T& operator * ();
    T* operator -> ();
  2. Design copy constructor and overload of ‘=’ to realize the requirement that a piece of memory has only one pointer identifier.

     SmartPointer<T>& operator = (const  SmartPointer<T>& obj   );
     SmartPointer( const SmartPointer<T>&  obj  );

3.2 class implementation


  template< typename  T>
  class SmartPointer
  {
  protected:
     T*   m_pointer;
  public:
 ​
      SmartPointer( T*  p=nullptr  )
      {
        m_pointer = p;
      }
 ​
      SmartPointer( const SmartPointer<T>&  obj  )
      {
         m_pointer= obj.m_pointer;
        const_cast< SmartPointer<T>& >( obj).m_pointer =nullptr;
      }
 ​
      SmartPointer<T>& operator = (const  SmartPointer<T>& obj)
      {
          if( this != &obj)
          {
          delete m_pointer;
          m_pointer= obj.m_pointer;
          const_cast<const SmartPointer<T>&  >( obj).m_pointer =nullptr;
          }
          return  *this;
      }
 ​
      T& operator * ()
      {
      return  *m_pointer;
      }
      T* operator -> ()
      {
      return m_pointer;
      }
 ​
      bool isNull()
      {
      return (m_pointer == nullptr) ;
      }
     ​
      T*  getPointer()
      {
      return m_pointer;
      }
     ​
      ~SmartPointer()
      {
      delete m_pointer;
      }
 ​
  };
  

Recommended Today

Talk about the secret of redis’s ziplist

Reference for this blog: Redis deep Adventure: core principles and application practice Detailed explanation of redis internal data structure (4) — ziplist Zip list of redis In the last blog, I gave you a quick introduction to the mysteries of SDS in redis, explaining that there is another very important but often overlooked point about […]