q0987
q0987

Reputation: 35982

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

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

Question> When we define the Line 1 which type is used for replacing type typename T? My understanding is that the type class Y is replaced by std::string when we initialize a boost::shared_ptr. Now, the question is that why we don't have to provide a type T? If we do it implicitly, where?

Thank you

Upvotes: 1

Views: 298

Answers (1)

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 506975

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* is the thing you passed to the constructor, and Y is deduced from that argument. T is part of the smart pointer type and provides type checking when you pass the shared_ptr around. void will completely erase any type information at compile time. While if you use std::string you completely preserve any type information (unless you would pass the constructor a class derived from std::string, in which case of course some information is again erased).

Shared ptr remembers the Y* passed to its constructor and using virtual calls or equivalent mechanisms it is able to call correct destructors when all Shared ptr copies die.

Upvotes: 3

Related Questions