首先编写SmartPointer.h
#ifndef SMARTPOINTER_H #define SMARTPOINTER_H namespace MyLib { template<typename T> class SmartPointer { protected: T* m_pointer; public: SmartPointer(T* p=NULL){ m_pointer = p; } //指针生命周期结束,主动释放空间 ~SmartPointer(){ delete 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 *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 <iostream> #include <smartpointer.h> using namespace std; using namespace MyLib; class Test { public: Test() { cout<<"Test()"<<endl; } ~Test(){ cout<<"~Test()"<<endl; } }; int main() { SmartPointer<Test> sp = new Test(); return 0; }
运行,实现简单的智能指针功能