I'm experiencing a crash when trying to dynamic_pointer_cast a shared point of type A to type B.
Type B is not related to type A and I'd expect an empty shared_ptr but instead, the exception above is raised.
Is there any scenario where it isn't safe to use dynamic_pointer_cast?
Exception raised here:
Using MSVC 14.16.27023
std::dynamic_pointer_cast requires that the conversion of U* (source) to T* (destination) is well formed. If it isn't then you have undefined behavior. If you want to get a null pointer like you would from dynamic_cast then you are going to have to write your own version that will do this.
Another option is test the result of
dynamic_cast<decltype(destination_ptr.get())>(source_ptr.get())
And if that succeeds then call std::dynamic_pointer_cast else return a null pointer.
User contributions licensed under CC BY-SA 3.0