智能指针提供了一种安全的处理对象指针及正确的回收对象指针内存的方法,本文给出了一个智能指针模板类,并给出了一个简单的实例
- ////////////////////////////SmartPoint.h///////////////////////////////////
- #ifndefSMARTPOINT_H_
- #defineSMARTPOINT_H_
- template<classT>
- classmem_ptr
- {
- T*m_p;
- mem_ptr(T&);
- public:
- mem_ptr():m_p(0){}
- mem_ptr(T*p):m_p(p){}
- ~mem_ptr(){deletem_p;}
- inlineT&operator*()const{return*m_p;}
- inlineT*operator->()const{returnm_p;}
- inlineoperatorT*()const{returnm_p;}
- inlineconstmem_ptr<T>&operator=(T*p){set(p);return*this;}
- inlineT*set(T*p){deletem_p;m_p=p;returnm_p;}
- inlineT*get()const{returnm_p;}
- inlinevoidrelease(){m_p=0;}
- inlineboolempty()const{returnm_p==0;}
- };
- #endif
- ///////////////////////TestSmart.h///////////////////////////////////////
- #include<iostream>
- usingnamespacestd;
- classA
- {
- public:
- A(inta,intb):m_a(a),m_b(b)
- {
- }
- voidShow()
- {
- cout<<m_a<<endl;
- cout<<m_b<<endl;
- }
- private:
- intm_a;
- intm_b;
- };
- ///////////////////////////main.cpp///////////////////////////////////////
- #include"SmartPoint.h"
- #include"TestSmart.h"
- voidmain()
- {
- mem_ptr<A>m_A=newA(1,2);
- m_A->Show();
- //程序退出时调用m_A的析构函数释放对象A的内存
- }