【问题标题】:enable_shared_from_this and inheritanceenable_shared_from_this 和继承
【发布时间】:2011-05-28 08:17:30
【问题描述】:

我有一个继承自enable_shared_from_this<type> 的类型,还有一个继承自该类型的类型。现在我不能使用 shared_from_this 方法,因为它返回基类型,并且在特定的派生类方法中我需要派生类型。直接从这里构造一个 shared_ptr 是否有效?

编辑: 在一个相关的问题中,如何从shared_ptr<base> 类型的右值移动到shared_ptr<derived> 类型?我使用 dynamic_cast 来验证它确实是正确的类型,但现在我似乎无法完成实际的移动。

【问题讨论】:

    标签: c++ boost c++11 shared-ptr smart-pointers


    【解决方案1】:

    获得shared_ptr<Base>后,您可以使用static_pointer_cast将其转换为shared_ptr<Derived>

    你不能直接从this 创建一个shared_ptr;这相当于:

    shared_ptr<T> x(new T());
    shared_ptr<T> y(x.get()); // now you have two separate reference counts
    

    【讨论】:

    • 不,您不能将shared_ptr&lt;Base&gt; 转换为shared_ptr&lt;Derived&gt;static_pointer_cast。必须使用dynamic_pointer_cast,因为可能有任意数量的派生类。
    • @Myon 为什么不呢?什么意思?
    • @curiousguy:如果您使用非虚拟继承并且您 100% 确定要转换的类型,则可以使用 static_pointer_cast。任何其他情况都是未定义的行为。所以一般使用dynamic_pointer_cast,你会很安全——这就是我要说的。
    猜你喜欢
    • 1970-01-01
    • 2013-04-11
    • 2020-11-11
    • 2018-04-27
    • 2021-11-11
    • 2016-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多