gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 01:49:42 26 4
gpt4 key购买 nike

我将在我的项目中使用向下转换,以便将一个 boost::shared_ptr<> 转换为类层次结构中的另一个。那是我使用 boost/polymorphic_pointer_cast 的测试代码和 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多态向下转换与静态向下转换一样高效,但确实在 Debug模式下添加了额外的运行时类型检查:

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 版本只是为智能指针类型增加了通用性,但上面的文档未更改地适用于这些版本。)

关于c++ - 向下转换 boost::polymorphic_pointer_downcast 或 boost::dynamic_pointer_cast 哪个更好用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43482591/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com