【问题标题】:weak_ptr of a base class, while the shared_ptr is of a derived class?基类的weak_ptr,而shared_ptr 是派生类的?
【发布时间】:2013-02-06 03:38:14
【问题描述】:

我有一个管理从基类Entity 派生的对象的结构,但不控制它们的生命周期。我希望这个结构被赋予像weak_ptr<Entity> 这样的弱指针,以便它可以知道对象是否已在其他地方被破坏。

但是,在共享指针所在的管理结构之外,我希望共享指针是更具体的shared_ptr<SpecificEntity>(SpecificEntity 使用 Entity 作为基类)。

有没有办法做到这一点,或者类似的东西?

【问题讨论】:

    标签: c++ templates inheritance c++11 shared-ptr


    【解决方案1】:

    这很有可能。您始终可以将shared_ptr<Derived> 隐式转换为shared_ptr<Base>,而对于另一个方向,您有std::static_pointer_cast 和std::dynamic_pointer_cast,它们可以满足您的期望——即您最终会得到一个不同类型的新指针与原始指针共享所有权。示例:

    std::shared_ptr<Base> p(new Derived);
    
    std::shared_ptr<Derived> q = std::static_pointer_cast<Derived>(p);
    
    std::shared_ptr<Base> r = q;
    

    或者,更多 C++11 风格:

    auto p0 = std::make_shared<Derived>();
    
    std::shared_ptr<Base> p = p0;
    
    auto q = std::static_pointer_cast<Derived>(p);
    

    【讨论】:

    • 啊,我不知道有演员表!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2016-02-24
    • 2015-07-23
    • 2017-05-01
    • 2018-02-25
    • 2021-06-15
    • 2011-09-05
    • 2012-06-01
    • 2013-08-02
    相关资源
    最近更新 更多