2016-06-13 67 views
4

爲什麼auto_ptr中有模板拷貝構造函數和覆蓋操作符函數?爲什麼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();OK

+0

很顯然,這些方法可以使用(可能)不同的模板類型。你的版本只是一樣的。 – deviantfan

回答

7

使用模板複製構造函數,我們可以初始化auto_ptrBase類的類型爲Derived一。沒有它auto_ptr<Base>auto_ptr<Derived>是完全不相關的類型。

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

auto_ptr<Derived> d(new Derived); 
auto_ptr<Base> b = d; 
相關問題