Re: Help to remove reinterpret_cast from c++ code
On 2013-04-24 02:15, nvangogh wrote:
Hi, I have been reading a class that I found online that creates an
object to represent a joystick. Now i recall reading that any use of
'reinterpret cast' is dangerous as it is highly machine
dependent. The code I found unfortunately uses this and i was hoping
to improve it, before attempting to use the class in my
program. Note, I have not tested the class as yet - even on the
assumption it works on my machine, i need it to be as general as
possible as my program will run on other machines as well.
This is the offending member function definition:
//loop function attempts to read an event from the device, and, if
//an event is waiting to be processed,
//updates the state structure based on the event type.
void* cJoystick::loop(void *obj)
{
while (reinterpret_cast<cJoystick *>(obj)->active)
reinterpret_cast<cJoystick *>(obj)->readEv();
}
What does this function return?
- so how can this be re-written so there are no re-interpret casts?
Technically you could rewrite this as:
void* cJoystick::loop(void* obj)
{
cJoystick& pJ = *static_cast<cJoystick*>(obj);
while (pJ.active)
pJ.readEv();
return nullptr; // Or whatever is right here
}
I find this more readable, but it still has the basically the same
meaning as the alternative version with the reinterpret_cast (modulo
some minor details that I think are not relevant in the context of
your question) and also cannot validate what you are doing here.
I assume you wrote this function with opaque parameters, because you
have to adapt to some low-level API. Instead of investing much efforts
to replace the reinterpret_cast here by static_cast, I recommend to
invest time to design a public API that does not depend on such
low-level details, instead wrapping this part into a layer that has
full control over the input and output of such functions. std::thread
is a good example for this: It completely hides the OS layer that
typically has exactly similar internal APIs as your cJoystick class.
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]