我试图通过从头开始实现 shared_ptr 来了解它的工作原理,但我不知道如何检测 T 的基类。
我试过使用 is_base_of(),但它给出了一个 const 值,我不能将其与 if 语句一起使用来设置对象的内部 weak_ptr。
我是这么想的:
template <class T>
class shared_ptr
{
shared_ptr(T* ptr)
{
...
}
shared_ptr(enable_shared_from_this<T>* ptr)
{
...
Ptr->m_this = weak_ptr<T>(this);
}
};
但到目前为止运气不好。 Boost 和 VC++ 的实现对我来说太困惑了,我正在寻找一个简单的解释。
Here它说
The constructors of std::shared_ptr detect the presence of an enable_shared_from_this base and assign the newly created std::shared_ptr to the internally stored weak reference.
是啊,怎么样?
最佳答案
简单 - 使用模板参数推导!那是世界上所有问题的解决方案,但您已经知道了:) 下面是基于 boost 解决问题方式的解决方案。我们创建了一个模板化的助手类,它实际上处理构造的细节。
template <class T>
class shared_ptr
{
shared_ptr(T* ptr)
{
magic_construct(this, ptr, ptr);
}
};
template <class X, class Y, class Z>
void magic_construct(shared_ptr<X>* sp, Y* rp, enable_shared_from_this<Z>* shareable)
{
//Do the weak_ptr handling here
}
void magic_construct(...)//This is the default case
{
//This is the case where you have no inheritance from enable_shared_from_this
}
关于c++ - shared_ptr<T> 如何检测到 T 派生自 enable_shared_from_this<T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26317387/