Re: Handling void*
Daniel Blankensteiner wrote:
I have two questions I hope you can help me with.
1. What is the correct way of returning void*?
if I have:
void* creatClass() {
return new Class();
}
Should I use reinterpret_cast?
No, you shouldn't use void in the first place. Otherwise, in above code, you
can use a static_cast<Class*> to get back the original pointer.
2. Can I at runtime check a cast from void* to a function(pointer)?
No. One more reason not to use it. If you used a polymorphic[1] baseclass,
you could use a dynamic_cast which would provide the type checking you
want.
void func(void* f) {
//f is a pointer to a function that I want to call, but I want to make
sure it is safe.
}
There is no way to make sure that f points to a Class object from inside
func(). You can only hope that func() is never called with anything else.
Note that while using void pointer isn't advisable, it is still pretty
common when using callbacks. There, you often pass in a function pointer
and a void pointer as context, which you then cast back to the intended
type.
Uli
[1] i.e. with at least one virtual function
--
Sator Laser GmbH
Gesch??ftsf??hrer: Thorsten F??cking, Amtsgericht Hamburg HR B62 932
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]