dynamic_pointer_cast 文档
文档来源:https://en.cppreference.com/w/cpp/memory/shared_ptr/pointer_cast
template< class T, class U >
std::shared_ptr<T> static_pointer_cast( const std::shared_ptr<U>& r ) noexcept;
...
Creates a new instance of std::shared_ptr whose stored pointer is obtained from
r
's stored pointer using a cast expression.If
r
is empty, so is the new shared_ptr (but its stored pointer is not necessarily null). Otherwise, the new shared_ptr will share ownership with the initial value ofr
, except that it is empty if the dynamic_cast performed by dynamic_pointer_cast returns a null pointer. Let Y betypename std::shared_ptr<T>::element_type
, then the resulting std::shared_ptr's stored pointer will be obtained by evaluating, respectively: 1,2)static_cast<Y*>(r.get())
3,4)dynamic_cast<Y*>(r.get())
. If the result of the dynamic_cast is a null pointer value, the returned shared_ptr will be empty. 5,6)const_cast<Y*>(r.get())
7,8)reinterpret_cast<Y*>(r.get())
The behavior of these functions is undefined unless the corresponding cast from U to T is well formed: 1,2) The behavior is undefined unless
static_cast<T*>((U*)nullptr)
is well formed. 3,4) The behavior is undefined unlessdynamic_cast<T*>((U*)nullptr)
is well formed. 5,6) The behavior is undefined unlessconst_cast<T*>((U*)nullptr)
is well formed. 7,8) The behavior is undefined unlessreinterpret_cast<T*>((U*)nullptr)
is well formed.After calling the rvalue overloads (2,4,6,8),
r
is empty andr.get() == nullptr
, except that r is not modified for dynamic_pointer_cast (4) if the dynamic_cast fails.
动态转换
来源:https://stackoverflow.com/questions/23795265/dynamic-cast-across-a-shared-ptr
If you just want to call a function from
B
you can use one of these:
std::shared_ptr<A> ap = ...;
dynamic_cast<B&>(*ap).b_function();
if (B* bp = dynamic_cast<B*>(ap.get()) {
...
}
In case you actually want to get a std::shared_ptr<B>
from the std::shared_ptr<A>
, you can use use
std::shared_ptr<B> bp = std::dynamic_pointer_cast<B>(ap);
方法二 std::dynamic_cast
class A {
};
class B: public A {
}
int main() {
std::shared_ptr<A> pb = std::make_shared<B>();
auto x = dynamic_cast<B*>(pb.get());
if(nullptr != x) {
//
}
}
方法三 std::dynamic_pointer_cast
转换为 shared_ptr
If you just want to call a function from B you can use one of these:
std::shared_ptr<A> ap = ...;
dynamic_cast<B&>(*ap).b_function();
if (B* bp = dynamic_cast<B*>(ap.get()) {
...
}
In case you actually want to get a std::shared_ptr from the std::shared_ptr, you can use use
std::shared_ptr<B> bp = std::dynamic_pointer_cast<B>(ap);