2010-07-23 25 views
5

聲明從C++標準庫空結構背後的目的是什麼?的auto_ptr

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>) 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> struct auto_ptr_ref {}; 

沒有宣佈任何變量,如何能夠將這些有效:

auto_ptr&      operator=(auto_ptr_ref<X>) throw(); 

這些也是:

auto_ptr(auto_ptr_ref<X>) throw(); 
    template <class Y> operator auto_ptr_ref<Y>() throw(); 

編輯:也(我注意到),我不知道如何「操作員」用於最後兩行。是不是語法像「返回類型operatoroperand;」,其中是返回類型?操作數?

+0

啊我根本就不知道那個雖然(這裏還是新手) – user385261 2010-07-23 09:09:54

+1

@ user385261:當你是一個網站的新手時,請閱讀他們的FAQ。這不是踢腿。 – 2011-09-09 09:17:43

回答

4

谷歌搜索「auto_ptr_ref」顯示this detailed explanation

我不太明白這個解釋,但看起來像下面這樣。如果沒有這個技巧,你可以將auto_ptr傳遞給一個函數,該函數將獲得對象的所有權並將你的變量賦給一個空指針。有了上面的額外類別技巧,在這種情況下您將收到編譯錯誤。

3

您已複製auto_ptr上的維基百科條目的文本,是不是?這只是公共接口auto_ptr和co。,而不是實施的摘錄。他們將文章中的auto_ptr_ref機身留空,以表示圖庫的用戶正在注意。

最後兩行這裏:

template <class Y> operator auto_ptr_ref<Y>() throw(); 
template <class Y> operator auto_ptr<Y>() throw(); 

的轉換操作符。轉換操作符的語法不同的一點,因爲它是沒有意義的聲明converion運算符(它的名字了!)的返回類型,所以你不寫int operator int();只是operator int();

如果你需要一個討論在auto_ref中auto_ptr_ref是如何使用的,SO有幾個。例如這裏: what is auto_ptr_ref, what it achieves and how it achieves it