[英]What is the use of dynamic_pointer_cast in C++? When is it used? What are alternatives for dynamic_pointer_cast?
I was reading about dynamic_pointer_cast.我正在阅读有关 dynamic_pointer_cast 的信息。 I found that we can dynamically upcast or downcast the shared pointer of one type to another at run time but i did't understand the concept completely.
我发现我们可以在运行时动态地将一种类型的共享指针向上或向下转换为另一种类型,但我并不完全理解这个概念。 Shall both the classes must have same properties?
两个类是否必须具有相同的属性? If the properties must be same then what is need of dynamic casting?
如果属性必须相同,那么动态转换需要什么?
dynamic_pointer_cast
is used to convert std::shared_ptr
type, eg from the pointer on a base class to a pointer on a derived class: dynamic_pointer_cast
用于转换std::shared_ptr
类型,例如从基类上的指针到派生类上的指针:
#include <memory>
struct A{ virtual ~A() = default; };
struct B: A {};
int main()
{
std::shared_ptr<A> pA = std::make_shared<B>();
std::shared_ptr<B> pB = std::dynamic_pointer_cast<B>(pA);
}
So dynamic_pointer_cast
is a convenience wrapper around dynamic_cast
:所以
dynamic_pointer_cast
是一个围绕dynamic_cast
的便利包装器:
template< class T, class U >
std::shared_ptr<T> dynamic_pointer_cast( const std::shared_ptr<U>& r ) noexcept
{
if (auto p = dynamic_cast<typename std::shared_ptr<T>::element_type*>(r.get())) {
return std::shared_ptr<T>{r, p};
} else {
return std::shared_ptr<T>{};
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.