C++ 泛型指针 auto_ptr

来源:互联网 发布:不合格品的数据分析 编辑:程序博客网 时间:2024/06/05 08:23
Code:
  1. #include <iostream>  
  2.   
  3. using namespace std;  
  4.   
  5. template <class T>  
  6. class myauto_ptr  
  7. {  
  8.     public :  
  9.         explicit myauto_ptr(T *p = 0) throw()  
  10.             :m_ptr(p) {}  
  11.         myauto_ptr(myauto_ptr<T> ©) throw()  
  12.             :m_ptr(copy.release()) {}  
  13.         myauto_ptr<T>& operator=(myauto_ptr<T> &other) throw()    
  14.         {  
  15.             if (this != &other)  
  16.             {  
  17.                 delete m_ptr;  
  18.                 m_ptr = other.release();  
  19.             }  
  20.             return *this;  
  21.         }  
  22.         ~myauto_ptr() { delete m_ptr;}  
  23.           
  24.         T& operator*() const throw() { return *m_ptr; }  
  25.         T* operator->() const throw() { return m_ptr; }  
  26.         T* get() const throw() { return m_ptr; }  
  27.         void reset(T *p = 0) throw()   
  28.         {   
  29.             if (m_ptr != p)  
  30.             {  
  31.                 delete m_ptr;  
  32.                 m_ptr = p;  
  33.             }  
  34.         }  
  35.         T* release() throw()  
  36.         {  
  37.             T *temp = m_ptr;  
  38.             delete m_ptr;  
  39.             //m_ptr = 0;     //省掉这句会有什么效果???  
  40.             return temp;  
  41.         }  
  42.     private:      
  43.         T *m_ptr;  
  44. };  
  45.   
  46. int main()  
  47. {  
  48.     myauto_ptr<int> pi(new int(1024));  
  49.     cout <<"pi:" << *pi << endl;  
  50.     myauto_ptr<int> pi1(pi);  
  51.     cout << "pi:" << *pi << endl;  
  52.     myauto_ptr<int> pi2(new int(2048));  
  53.     cout << *pi2 << endl;  
  54.     if (pi.get())  
  55.         *pi = 1024;  
  56.     else  
  57.         pi.reset(new int(1024));  
  58.     cout << *pi << endl;  
  59.     return EXIT_SUCCESS;  
  60. }  

第一次发表笔记,这是泛型指针的实现,属于异常安全的

但是不能用于STL泛型容器中,因为其copy 构造和赋值操作具有破坏性,不符合STL泛型容器的要求

但也可以修改myauto_ptr的copy construct 和 copy assignment,使其符合STL泛型容器的要求,但存在危险