哪个模板参数在带有原始指针的boost :: shared_ptr构造函数中使用

时间:2011-12-23 21:32:31

标签: c++ boost

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

问题&GT;当我们定义第1行时,哪种类型用于替换类型typename T?我的理解是,当我们初始化class Y时,std::string类型被boost::shared_ptr替换。现在,问题是为什么我们不必提供类型T?如果我们隐含地这样做,在哪里?

谢谢

1 个答案:

答案 0 :(得分: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*并使用虚拟调用或等效机制,当所有Shared ptr副本都死掉时,它能够调用正确的析构函数。