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

which template parameter is used in boost::shared_ptr constructor with a raw pointer

本文关键字:指针 原始 一个 ptr 形参 boost shared 构造函数      更新时间:2023-10-16
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 Ystd::string取代。现在的问题是,为什么我们不需要提供类型T ?如果我们隐式地做,在哪里?

谢谢

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派生的类传递给构造函数,在这种情况下,当然会再次擦除某些信息)。

Shared ptr保存传递给其构造函数的Y*,并且使用虚调用或等效机制,当所有Shared ptr副本死亡时,它能够调用正确的析构函数。