2011-12-23 13 views
1
namespace boost { 

    template<typename T> class shared_ptr { // I have problems to understand the T 
    public: 
    template <class Y> explicit shared_ptr(Y* p); 
    template <class Y,class D> shared_ptr(Y* p,D d); 

    ~shared_ptr(); 

    shared_ptr(const shared_ptr & r); 
    template <class Y> explicit 
     shared_ptr(const weak_ptr<Y>& r); 
    template <class Y> explicit shared_ptr(std::auto_ptr<Y>& r); 

    shared_ptr& operator=(const shared_ptr& r); 

    void reset(); 

    T& operator*() const; 
    T* operator->() const; 
    T* get() const; 

    bool unique() const; 
    long use_count() const; 

    operator unspecified-bool-type() const; 

    void swap(shared_ptr<T>& b); 
    }; 

    template <class T,class U> 
    shared_ptr<T> static_pointer_cast(const shared_ptr<U>& r); 
} 

Example of the usage of boost::shared_ptr:  
    boost::shared_ptr<std::string> ptr(new std::string("hello world")); // Line 1 

質問>我々はタイプtypename Tを交換するために使用されるタイプライン1を定義するとき?私が理解しているのは、タイプclass Yは、boost::shared_ptrを初期化すると、std::stringに置き換えられます。さて、問題はなぜ我々はタイプTを提供する必要がないということですか?私たちが暗黙のうちにそれをしたら、どこ?::生のポインタとのshared_ptrのコンストラクタ

答えて

3
boost::shared_ptr<std::string> ptr(new std::string("hello world")); 
//    TTTTTTTTTTT  YYYYYYYYYYYYYYYYYYYYYYYYYYYYYY 


boost::shared_ptr<void> ptr(new std::string("hello world")); 
//    TTTT  YYYYYYYYYYYYYYYYYYYYYYYYYYYYYY 

Y*あなたは、コンストラクタに渡されたもので、Yは、その引数から推論された、ありがとうございました。 Tは、スマートポインタ型の一部であり、shared_ptrを渡すときに型チェックを行います。 voidは、コンパイル時にすべてのタイプ情報を完全に消去します。 std::stringを使用すると、コンストラクタにstd::stringから派生したクラスを渡す場合を除き、すべての型情報が完全に保持されますが、その場合はいくつかの情報が再度消去されます。

共有ptrは、コンストラクタに渡されたY*を覚えており、仮想呼び出しまたは同等のメカニズムを使用して、すべての共有ptrコピーが消滅したときに正しいデストラクタを呼び出すことができます。

関連する問題