哪个模板形参在boost::shared_ptr构造函数中使用一个原始指针
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
问题>当我们定义第1行时,哪个类型用于替换类型typename T
?我的理解是,当我们初始化boost::shared_ptr
时,类型class Y
被std::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副本死亡时,它能够调用正确的析构函数。
相关文章:
- 是否可以将llvm::FunctionType转换为C/C++原始函数指针
- 从堆栈分配的原始指针构造智能指针
- 将unique_ptr分配给原始指针
- 如何将唯一指针的 std::vector 转换为原始指针的 std::span?
- <Base> <Derived> 具有相同原始指针共享引用的 shared_ptr 和 shared_ptr 实例是否计数?
- C++原始指针和"delete"
- 为什么 C++ 地址中的矢量无法通过原始指针访问
- 复制后删除原始数组指针将前 3 个字节设置为 0
- 如何正确实现具有原始指针的类的复制构造函数?
- 如何在将原始指针移动到基类构造函数之前从unique_ptr中提取原始指针
- C++指针无法更改其原始值
- 为包含原始指针的对象C++智能指针
- unique_ptr<T>::get() 返回的指针在原始unique_ptr被销毁后不是 nullptr
- c++:复制、删除和运算符=在原始指针映射中
- C++模板,用于通过常量引用和原始指针传递向量
- C++为什么原始指针不会增加shared_ptr的引用计数?
- 从shared_ptr获取原始指针以将其传递给需要 raw 的函数
- 如何包装多级原始指针以赋予其容器语义
- 为什么我可以通过原始指针而不是shared_ptr来修改对象
- Qt - 将空指针(原始数据)转换为 QImage 并将其显示在标签上