向下转换 boost::polymorphic_pointer_downcast 或 boost::dynamic_pointer_cast 哪个更好用

What is better to use for downcasting boost::polymorphic_pointer_downcast or boost::dynamic_pointer_cast

我将在我的项目中使用向下转换,以便将一个 boost::shared_ptr<> 转换为 class 层次结构中的另一个。那是我使用 boost/polymorphic_pointer_cast and boost::dynamic_pointer_cast 两种变体工作的测试代码。但是我不明白它们之间有什么区别。你能描述一下 boost::polymorphic_pointer_downcastboost::dynamic_pointer_cast 之间的区别吗?

namespace cast
{

class Base
{
public:
    virtual void kind() { std::cout << "base" << std::endl; }
};

class Derived : public Base
{
public:
    virtual void kind2() { std::cout << "derived" << std::endl; }
};

}

int main(int argc, char* argv[])
{
    try
    {
        boost::shared_ptr<cast::Base> base(new cast::Derived());
        base->kind();

        boost::shared_ptr<cast::Derived> d1 = boost::polymorphic_pointer_downcast<cast::Derived>(base);
        d1->kind();
        d1->kind2();

        boost::shared_ptr<cast::Derived> d2 = boost::dynamic_pointer_cast<cast::Derived>(base);
        d2->kind();
        d2->kind2();
    }
    catch (const std::exception& e)
    {
        std::cerr << "Error occurred: " << e.what() << std::endl;
    }

    return 0;
}

谢谢。

根据 docs 多态向下转换与静态向下转换一样高效,但确实在调试模式下添加了额外的运行时类型检查:

The C++ built-in static_cast can be used for efficiently downcasting pointers to polymorphic objects, but provides no error detection for the case where the pointer being cast actually points to the wrong derived class. The polymorphic_downcast template retains the efficiency of static_cast for non-debug compilations, but for debug compilations adds safety via an assert() that a dynamic_cast succeeds

合乎逻辑的结果是

A polymorphic_downcast should be used for downcasts that you are certain should succeed

否则,使用boost::dynamic_pointer_cast


(注意 *_pointer_*cast 版本只是增加了智能指针类型的通用性,但上面的文档未更改地适用于这些版本。)