Downcasting shared_ptr<Base> to shared_ptr?

前端 未结 3 1481
温柔的废话
温柔的废话 2020-11-30 20:28

Update: the shared_ptr in this example is like the one in Boost, but it doesn\'t support shared_polymorphic_downcast (or dynamic_pointer_cast or static_pointer_cas

3条回答
  •  有刺的猬
    2020-11-30 20:46

    If somebody gets here with boost::shared_ptr...

    This is how you can downcast to the derived Boost shared_ptr. Assuming Derived inherits from Base.

    boost::shared_ptr bS;
    bS.reset(new Derived());
    
    boost::shared_ptr dS = boost::dynamic_pointer_cast(bS);
    std::cout << "DerivedSPtr  is: " << std::boolalpha << (dS.get() != 0) << std::endl;
    

    Make sure 'Base' class/struct has at least one virtual function. A virtual destructor also works.

提交回复
热议问题