4

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

The ISO standard for C++ specifies the following interface for auto_ptr. (This is copied straight out of the 2003 standard.)

  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();
    };

why there are:

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

I think just auto_ptr(auto_ptr&) throw(); is ok.

BlackMamba
  • 10,054
  • 7
  • 44
  • 67
  • Obviously, these methods work with a (possibly) different template type. Your version is only for the same. – deviantfan Jun 13 '16 at 05:40

1 Answers1

7

With template copy constructor we can initialize auto_ptr of Base class type by Derived one. Without it auto_ptr<Base> and auto_ptr<Derived> are completely unrelated types.

struct Base {};
struct Derived : Base {};

auto_ptr<Derived> d(new Derived);
auto_ptr<Base> b = d;
Ashot
  • 10,807
  • 14
  • 66
  • 117