标签:
在单位写代码没法用c++11,为了方便写代码,今天趁着空闲时间写了个unique_ptr的简单实现
//default deleter for unique_ptr template<typename T> struct DefaultDeleter { void operator()(T *p) { if (p) { delete p; p = NULL; } } }; template<typename T, typename Deleter = DefaultDeleter<T>> class unique_ptr { public: //construct unique_ptr(T *pT = NULL); //destroy ~unique_ptr(); //not allow copyable private: unique_ptr(const unique_ptr &); unique_ptr&operator=(const unique_ptr &); public: //reset void reset(T *p); //release the own of the pointer T *release(); //get the pointer T *get(); public: //convert unique_ptr to bool operator bool() const; //overload for operator * T &operator*(); //overload for operator -> T *operator->(); private: //pointer T *m_pT; //deleter Deleter m_deleter; //call deleter void del(); }; //construct template<typename T, typename Deleter> unique_ptr<T, Deleter>::unique_ptr(T *pT) :m_pT(pT) { } //destroy template<typename T, typename Deleter> unique_ptr<T, Deleter>::~unique_ptr() { del(); } //call deleter template<typename T, typename Deleter> void unique_ptr<T, Deleter>::del() { if (*this) { m_deleter(m_pT); m_pT = NULL; } } //get the pointer template<typename T, typename Deleter> T *unique_ptr<T, Deleter>::get() { return m_pT; } //reset template<typename T, typename Deleter> void unique_ptr<T, Deleter>::reset(T *p) { del(); m_pT = p; } //release the own of the pointer template<typename T, typename Deleter> T *unique_ptr<T, Deleter>::release() { T *p = m_pT; m_pT = NULL; return p; } //convert unique_ptr to bool template<typename T, typename Deleter> unique_ptr<T, Deleter>::operator bool()const { return NULL != m_pT; } //overload for operator * template<typename T, typename Deleter> T &unique_ptr<T, Deleter>::operator*() { assert(*this); return *m_pT; } //overload for operator -> template<typename T, typename Deleter> T *unique_ptr<T, Deleter>::operator->() { return &*(*this); }
测试代码
#include <iostream> #include "unique_ptr.h" struct Obj { int m_nMyMem; Obj() { std::cout << "[NEWOBJ][Obj] this =" << this << std::endl; } ~Obj() { std::cout << "[DELOBJ][~Obj] this =" << this << std::endl; } }; int main(int argc,char *argv[]) { unique_ptr<Obj> uptr(new Obj); assert(uptr); uptr->m_nMyMem = 100; std::cout << "nMyMem= " << (*uptr).m_nMyMem << std::endl; auto p = uptr.release(); if (p) { delete p; p = NULL; } return 0; }
输出结果 ==>>
[NEWOBJ][Obj] this =00000000002C7D20
nMyMem= 100
[DELOBJ][~Obj] this =00000000002C7D20
标签:
原文地址:http://www.cnblogs.com/ywy2090/p/5808266.html