简体   繁体   中英

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

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_cast s with void* intermediate).

If you cast it to any type not allowed under those rules, eg 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.

my question is: is there a way to check if the static_cast succeeded?

No. It's either correct or your program will have undefined behavior .

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

Yes, exactly that. So, when using static_cast you must be sure that the void* is actually pointing at an object of the type you cast to (or is a legal up or down cast).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM