首先编写SmartPointer.h
#ifndef SMARTPOINTER_H#define SMARTPOINTER_Hnamespace MyLib {templateclass SmartPointer{protected: T* m_pointer;public: SmartPointer(T* p=NULL){ m_pointer = p; } //指针生命周期结束,主动释放空间 ~SmartPointer(){ delete m_pointer; } //直接赋值 SmartPointer(const SmartPointer & obj){ m_pointer =obj.m_pointer; //同一片堆空间只能由一个指针使用 const_cast &>(obj).m_pointer = NULL; } //=赋值 SmartPointer & operator=(const SmartPointer & obj){ if(this != &obj){ delete m_pointer; m_pointer =obj.m_pointer; //同一片堆空间只能由一个指针使用 const_cast &>(obj).m_pointer = NULL; } return *this; } T* operator->(){ return m_pointer; } T& operator *(){ return *m_pointer; } bool isNull(){ return m_pointer == NULL; } T* get(){ return m_pointer; }};}#endif // SMARTPOINTER_H
2. 测试代码:
#include#include using namespace std;using namespace MyLib;class Test{public: Test() { cout<<"Test()"< sp = new Test(); return 0;}
运行,实现简单的智能指针功能