Re: c++ casting issues
On Mar 20, 2:10 am, Christopher <cp...@austin.rr.com> wrote:
On Mar 19, 4:48 pm, Juha Nieminen <nos...@thanks.invalid> wrote:
Don't use void* at all. You are only asking for problems.
I disagree. Sometimes it is now avoidable to use a void *,
especially when using the Windows API as they force you to in
some of thier function calls.
Not just Windows. A lot of the Posix API uses void* as well.
Whenever there is a callback in a C API, it is traditional to
add void* for user data---typically, in C++, this will be a
pointer to a class, and the `extern "C"' function which we pass
to the callback will convert the pointer back to the class
type, and call a member function on it.
In such cases, it is very, very important to explicitly cast the
actual pointer to the type used in the callback function before
passing it. A typical scenario might be (using pthread_create,
from the Posix interface):
extern "C" void* threadStarter( void* p )
return static_cast< ThreadBase* >( p )->run() ;
class MyThread : public ThreadBase
MyThread newThread ;
pthread_create( &threadId, NULL, threadStarter,
static_cast< ThreadBase* >( &newThread ) ) ;
Without the static_cast in the call, the code has undefined
behavior. (In this particular case, of course, and even better
solution would be to use boost::threads:-). But it serves as a
It is often necessary to use void * and a reinterpret_cast to
Not reinterpret_cast, static_cast.
It is frowned upon and should be avoided _if possible_.
Obviously, if you don't have a choice, you don't have a choice.
James Kanze (GABI Software) email:email@example.com
Conseils en informatique orient=EF=BF=BDe objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=EF=BF=BDmard, 78210 St.-Cyr-l'=EF=BF=BDcole, France, +33 (0)1 30 2=
3 00 34