Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a safe way to cast void* to class pointer in C++

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading