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
Y*is the thing you passed to the constructor, andYis deduced from that argument.Tis part of the smart pointer type and provides type checking when you pass theshared_ptraround.voidwill completely erase any type information at compile time. While if you usestd::stringyou completely preserve any type information (unless you would pass the constructor a class derived fromstd::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.