Exception 0xC0000409 (stack buffer overflow) when using dynamic_pointer_cast

0

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:

enter image description here

Using MSVC 14.16.27023

c++
exception
visual-c++
dynamic-cast
asked on Stack Overflow Feb 21, 2020 by SagiLow

1 Answer

2

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.

answered on Stack Overflow Feb 21, 2020 by NathanOliver • edited Feb 21, 2020 by NathanOliver

User contributions licensed under CC BY-SA 3.0