8

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

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

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

4

1 回答 1

13

这是很有可能的。您始终可以将shared_ptr<Derived>ashared_ptr<Base>隐式转换为 a ,并且对于您拥有的另一个方向std::static_pointer_caststd::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);
于 2013-02-20T23:17:51.100 回答