Re: Handling void*
On Nov 5, 9:19 am, Daniel Blankensteiner <d...@trunet.dk> wrote:
Hi all
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 would use a static cast but thats not the better solution. Use
a template and you will not need void*'s. Basicly, void pointers strip
a compiler's ability to type check for you. Thats bad news.
#include <iostream>
#include <typeinfo>
class A { };
void* createA()
{
return static_cast< void* >(new A);
}
template< typename T >
T* const createT()
{
return new T;
}
int main()
{
A* p = static_cast< A* >(createA());
std::cout << "the object at *p is of type: ";
std::cout << typeid( *p ).name() << std::endl;
delete p // required
A* p_a = createT< A >();
// static_cast< void* >(p_a) here
// do stuff
delete p_a; // required
std::cout << "Press ENTER to EXIT.\n";
std::cin.get();
}
2. Can I at runtime check a cast from void* to a function(pointer)?
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.
}
Template the above function.
You can't tell a program to bypass type checking and then expect
safety. Thats like removing the batteries from a fire alarm and
expecting the fire alarm to still notify you in case of fire. Think of
void* as evil, if you must use it, do it in such a way that it doesn't
compromise your code.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]