C++ 智能指针auto_ptr

时间:2023-03-09 21:50:46
C++ 智能指针auto_ptr
template<class T>
  class auto_ptr {
  public:
   explicit auto_ptr(T *p = ); // Item M5 有“explicitfor”// 的描述
  
template<class U> // 拷贝构造函数成员模板
   auto_ptr(auto_ptr<U>& rhs); // (见Item M28):
   // 用另一个类型兼容的
   // auto_ptr对象
   // 初始化一个新的auto_ptr对象    ~auto_ptr();
   template<class U> // 赋值操作成员模板
   auto_ptr<T>& // (见Item M28):
   operator=(auto_ptr<U>& rhs); // 用另一个类型兼容的    // auto_ptr对象给它赋值
   T& operator*() const; // 见Item M28
   T* operator->() const; // 见Item M28
   T* get() const; // 返回包容指针的
   // 当前值
   T* release(); // 放弃包容指针的
   // 所有权,
   // 并返回其当前值
   void reset(T *p = ); // 删除包容指针,
   // 获得指针p的所有权
  private:
   T *pointee;   template<class U> // 让所有的auto_ptr类
  friend class auto_ptr<U>; // 成为友元   };
     //构造函数
  template<class T>
  inline auto_ptr<T>::auto_ptr(T *p)
  : pointee(p)
  {}
//拷贝构造函数
  template<class T>
   inline auto_ptr<T>::auto_ptr(auto_ptr<U>& rhs)
   : pointee(rhs.release())
   {}   template<class T>
  inline auto_ptr<T>::~auto_ptr()
  { delete pointee; }    template<class T>
   template<class U>
   inline auto_ptr<T>& auto_ptr<T>::operator=(auto_ptr<U>& rhs)
   {
   if (this != &rhs) reset(rhs.release());
   return *this;
   }   template<class T>
  inline T& auto_ptr<T>::operator*() const
  { return *pointee; }   template<class T>
  inline T* auto_ptr<T>::operator->() const
  { return pointee; }   template<class T>
  inline T* auto_ptr<T>::get() const
  { return pointee; }   template<class T>
  inline T* auto_ptr<T>::release()
  {
   T *oldPointee = pointee;
   pointee = ;
   return oldPointee;
  }   template<class T>
  inline void auto_ptr<T>::reset(T *p)
  {
   if (pointee != p) {
   delete pointee;
   pointee = p;
   }
  }

没看过stl源码剖析,感觉这个智能指针只是在自己要管理的内存资源上封装成类,这样利用对象解析时自动调用析构函数的思想,来保证delete的执行。

//摘自网上http://dbchu.com/2013/05/11/966

STL中智能指针 auto_ptr(C++98)所做的事情,就是动态分配对象以及当对象不再需要时自动执行清理。

但是auto_ptr有缺陷,在使用时要注意避免。

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

1、auto_ptr不能共享所有权。
2、auto_ptr不能指向数组
3、auto_ptr不能作为容器的成员。
4、不能通过赋值操作来初始化auto_ptr
std::auto_ptr<int> p(new int(42)); //OK
std::auto_ptr<int> p = new int(42); //ERROR
这是因为auto_ptr 的构造函数被定义为了explicit
5、不要把auto_ptr放入容器