gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:04:25 26 4
gpt4 key购买 nike

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 拷贝死亡时调用正确的析构函数。

关于c++ - 在带有原始指针的 boost::shared_ptr 构造函数中使用了哪个模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8620815/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com