Re: Help to remove reinterpret_cast from c++ code
Am 24.04.2013 02:15, schrieb nvangogh:
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.
Yes, use of reinterpret_cast always has a code smell.
This is the offending member function definition:
[...]
void* cJoystick::loop(void *obj)
{
while (reinterpret_cast<cJoystick *>(obj)->active)
reinterpret_cast<cJoystick *>(obj)->readEv();
}
pthread_create(&thread, 0, &cJoystick::loop, this);
Ah, and it is even used wrongly. The conversion from "this" to "void*"
is equivalent to a static_cast. In the loop function, it should do
this:
cJoystick* js = static_cast<cJoystick*>(obj);
while(...)
...
Of course, with modern C++ there's std::thread and thus no reason to
use the raw POSIX thread interface at all. Doing so would hide this
cast.
That said, the code smells in many other aspects:
- exception safety
- Law of Three
- not checking returnvalues/errorcodes
- not synchronizing access to resources shared between threads
- use of nonstandard __u8 types that should be uint8_t
- C-style casts
- public functions loop() and readEv() should be private
- const correctness of buttonPressed()
Uli
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]