I am using a C library and I’m passing a "user pointer" to it. When I want to obtain the user pointer the library returns it as void*. I’m currently using static_cast in order to de-reference the members of the original pointer.
So my question is: is there a way to check if the static_cast succeeded?
As far as I know static_cast will not return a nullptr on failure, but rather, if I attempt to de-reference the resulting failed pointer it would be UB and probably crash the program…
>Solution :
Yes, static_cast is correct here.
Assuming that the void* value is only copied inside the C library, static_cast will return the original pointer value pointing to the passed object if you cast it to a pointer of the same type as it was originally.
Under some conditions you may also cast to a different type, the rules are those of reinterpret_cast (which simply casts via two static_casts with void* intermediate).
If you cast it to any type not allowed under those rules, e.g. an unrelated class type, trying to access the object through the pointer will cause undefined behavior. There is no way of detecting this mistake. You need to take care of doing it correctly yourself.