为什么auto_ptr中有模板复制构造函数和覆盖运算符函数

why there are template copy constructor and override operator function in auto_ptr?

本文关键字:构造函数 复制 覆盖 函数 运算符 auto ptr 为什么      更新时间:2023-10-16

为什么auto_ptr中有模板复制构造函数和覆盖运算符函数?

C++的 ISO 标准为auto_ptr指定了以下接口。(这是直接从 2003 年标准复制而来的。

  namespace std {
    template <class Y> struct auto_ptr_ref {};
    template<class X> class auto_ptr {
    public:
      typedef X element_type;
      // 20.4.5.1 construct/copy/destroy:
      explicit auto_ptr(X* p =0) throw();
      auto_ptr(auto_ptr&) throw();
      template<class Y> auto_ptr(auto_ptr<Y>&) throw();
      auto_ptr& operator=(auto_ptr&) throw();
      template<class Y> auto_ptr& operator=(auto_ptr<Y>&) throw();
      auto_ptr& operator=(auto_ptr_ref<X> r) throw();
      ~auto_ptr() throw();
      // 20.4.5.2 members:
      X& operator*() const throw();
      X* operator->() const throw();
      X* get() const throw();
      X* release() throw();
      void reset(X* p =0) throw();
      // 20.4.5.3 conversions:
      auto_ptr(auto_ptr_ref<X>) throw();
      template<class Y> operator auto_ptr_ref<Y>() throw();
      template<class Y> operator auto_ptr<Y>() throw();
    };

为什么有:

template<class Y> auto_ptr(auto_ptr<Y>&) throw();

我认为只要auto_ptr(auto_ptr&) throw();就可以了。

使用模板复制构造函数,我们可以通过Derived类类型来初始化Base类类型的auto_ptr。没有它,auto_ptr<Base>auto_ptr<Derived>是完全不相关的类型。

struct Base {};
struct Derived : Base {};
auto_ptr<Derived> d(new Derived);
auto_ptr<Base> b = d;