简体   繁体   中英

Casting the proper way in C++

I apologise if this isn't considered a good enough question (since my own solution just works, so I don't actually have a problem), but here goes.
I mean, I was brought up on C and I only learned C++ later, so maybe I'm biased, but still.

In this particular case, there is one library that returns a const char* , while another library needs a void* as input. So if I want to call the second library with the result of the first, I will need to write

second(const_cast<void*>(static_cast<const void*>(first())));

Right? That's the only proper way, right?

A char* can be implicitly converted to a void* , so your code can be simplified to this:

second(const_cast<char*>(first()));

This is only safe if the definition of second operates as if its parameter had the type const void* .

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