Examples of smart pointers

Smart pointer class template is actually through a technology implementation

Memory leaks (the infamous Bug) - are not easily found in software development and testing
- Dynamic application heap, exhausted not return
-C ++ language is no mechanism for garbage collection
- pointer can not be controlled within the meaning of the heap lifecycle space

Modern C ++ software platform in smart pointers
- take the initiative to release the heap pointer at the end of the life cycle
- Up only a heap of a pointer identification

- eliminate the pointer and the pointer arithmetic comparison

Smart pointer design
- by class template describes the behavior of the pointer
  can define a different type of pointer object
- Overload characteristic operator pointer (-> and *) by using an object that simulates the behavior of native pointer
  

SmartPointer.h

 

#ifndef SMARTPOINTER_H_
#define SMARTPOINTER_H_

namespace DTLib
{
template <typename T>
class SmartPointer
{
protected:
    T* m_pointer;
public:
    SmartPointer(T* p =NULL)
    {
        m_pointer = p;
    }

    T* operator ->()
    {
        return m_pointer;
    }

    T& operator *()
    {
        return *m_pointer;
    }

    SmartPointer(const SmartPointer<T>& obj)
    {
        m_pointer = obj.m_pointer;
        const_cast<SmartPointer<T> &>(obj).m_pointer = NULL;
    }

    SmartPointer<T>& operator = (const SmartPointer<T>& obj)
    {
        if(this != &obj)
        {
            delete m_pointer;
            m_pointer = obj.m_pointer;
            const_cast<SmartPointer<T> &>(obj).m_pointer = NULL;
        }

        return * the this ;    // can support continuous assignment 
    }

    T* get()
    {
        return m_pointer;
    }

    bool isNull()
    {
        return (m_pointer == NULL);
    }

    ~SmartPointer()
    {
        delete m_pointer;
    }

};

}

#endif // SMARTPOINTER_H_

 

main.cpp

#include <iostream>
#include "SmartPointer.h"

using namespace std;
using namespace DTLib;

class Test
{
public:
    Test()
    {
        cout << "Test()" << endl;
    }
    ~Test()
    {
        cout << "~Test()" << endl;
    }


};

int main()
{

    SmartPointer<Test> sp = new Test();
    SmartPointer<Test> nsp;

    nsp = sp;
    cout << sp.isNull() << endl;
    cout << nsp.isNull() << endl;

    cout << "sp = " << sp.get() << endl;
    cout << "nsp = " << nsp.get() << endl;


    return 0;
}

智能指针的使用军规
只能用来指向堆空间中的单个对象或者变量
不能指向堆空间中的一个数组,也不能用来指向一个局部的对象或局部的变量

 

 

 

Guess you like

Origin www.cnblogs.com/-glb/p/12032012.html
Recommended