c++ - shared_ptr<T> 如何检测到 T 派生自 enable_shared_from_this<T>?

标签 c++ boost std shared-ptr enable-shared-from-this

我试图通过从头开始实现 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/

相关文章:

c++ - 针对非默认 glibc 的链接

c++ - boost::asio 接受器在 EOF 后重新打开和异步读取

c++ - 我如何包装 BOOST_CHECK_CLOSE?

c++ - 为什么编译器不能解析 std::function 参数的重载?

C++ 什么时候可以扩展 `std` 命名空间?

c++ - OpenMP 如何实现对临界区的访问?

c++ - 使用从未打算在常量表达式中使用的 constexpr 变量是否有好处?

c++ - 检查是否可以释放指针

c++ - 中断 boost::asio 同步读取?

c++ - 将 std::shared_ptr 传递给构造函数