我正在尝试从零开始实现 shared_ptr,并希望通过此过程了解其工作原理。然而,我无法弄清楚如何检测 T 的基类。
我已经尝试使用 is_base_of() 函数,但它返回的是一个 const 值,无法在 if 语句中使用并设置对象内部的 weak_ptr。
我的思路是这样的:
我已经尝试使用 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++的实现对我来说太混乱了,我正在寻找一个简单的解释。
这里说:
std::shared_ptr的构造函数检测到存在enable_shared_from_this基类,并将新创建的std::shared_ptr分配给内部存储的弱引用。
是啊,怎么做到的呢?
template <class Z> magic_construct(enable_shared_from_this<Z>* share)
是不够的?我为什么需要sp
和rp
参数? - Alex