auto_ptr的简单实现

[cpp]  view plain  copy
  1. #include <iostream>  
  2. #include <stack>  
  3. #include <stdio.h>  
  4.   
  5. using namespace std;  
  6.   
  7. template <class T>  
  8. class AutoPtr{  
  9. private:  
  10.     T *m_ptr;  
  11. public:  
  12.     explicit AutoPtr(T *p=0): m_ptr(p){}  
  13.     AutoPtr (AutoPtr &a):m_ptr(a.release()){}//拷贝构造函数,将原值拷贝,并设为0  
  14.   
  15.     AutoPtr &operator = (AutoPtr &a) {  
  16.         if(this == &a)  
  17.             return *this;  
  18.         delete m_ptr;  
  19.         m_ptr = a.release();  
  20.   
  21.         return *this;  
  22.     }  
  23.   
  24.     ~AutoPtr() {  
  25.         delete m_ptr;  
  26.     }  
  27.       
  28.     T& operator *(){  
  29.         return *m_ptr;  
  30.     }  
  31.   
  32.     T* operator ->() {  
  33.         return m_ptr;  
  34.     }  
  35.   
  36.     T *get() {  
  37.         return m_ptr;  
  38.     }  
  39.   
  40.     T* release() {//返回指针,并自己设为0  
  41.         T *tmp = m_ptr;  
  42.         m_ptr = 0;  
  43.         return tmp;  
  44.     }  
  45.   
  46.     void reset(T *p = 0) {  
  47.         if (p != m_ptr) {  
  48.             delete m_ptr;  
  49.             m_ptr = p;  
  50.         }  
  51.     }  
  52.   
  53.   
  54. };  
  55.   
  56. int main() {  
  57.     AutoPtr<int > t(new int(1));  
  58. }  

1.    auto_ptr重载了操作符&,*和->。不要被语法误导,记住pstr是一个对象,不是一个指针。只是它重载了这些操作符后, 使用上相指针一样.

2.    不要将auto_ptr对象作为STL容器的元素。C++标准明确禁止这样做,否则可能会碰到不可预见的结果

3.    不要将数组作为auto_ptr的参数, 可以理解到在auto_ptr中, 使用delete, 但没有使用delete [].

4. auto_ptr不能作为容器的成员。

5. 不能通过赋值操作来初始化auto_ptr

std::auto_ptr<int> p(new int(42));     // OK

std::auto_ptr<int> p = new int(42);    // ERROR

这是因为auto_ptr 的构造函数被定义为了explicit

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值