2011-12-23 2 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 

질문으로 우리가 1 호선 정의 할 때> 유형 유형 typename T 교체에 사용? 우리가 boost::shared_ptr을 초기화 할 때 class Y 유형이 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 복사본이 종료 될 때 올바른 소멸자를 호출 할 수 있습니다.

관련 문제