Casting the right way in C ++

I apologize if this is not considered a good enough question (since my own solution just works, so I really have no problem), but here it goes. I mean, I was raised in C, and later I learned C ++, so maybe I am biased, but still.

In this particular case, there is one library that returns const char* , and another library needs the input void* . Therefore, 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? This is the only right way, right?

+4
source share
1 answer

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

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

This is safe if the definition of second works as if its parameter were of type const void* .

+8
source

Source: https://habr.com/ru/post/1388906/


All Articles