Assigning a function pointer to a void
pointer,
double f_dummy(double x) { return x; }
...
void *pv = f_dummy; //compilation error
is illegal as explained in this FAQ. The answer, however, closes with the statement :
Please do not email me if the above seems to work on your particular version of your particular compiler on your particular operating system. I don’t care. It’s illegal, period.
Edit : As a warning to others, I did encounter this "seems to work" behavior, through a case of inheritance involving class templates. No compiler warning, no unexpected run-time behavior.
This tickles my OCD bone and makes me wonder if what I've been doing, e.g.,
...
auto l_func = [](double x){ return f_dummy(x); };
void *pv = &l_func;
auto pl = static_cast<decltype(&l_func)>(pv);
cout << (*pl)(5.) << endl;
which compiles and runs cleanly (g++ -std=c++11 -Wall
), is truly legal. Is it?
A void pointer is a pointer that can point to any type of object, but does not know what type of object it points to. A void pointer must be explicitly cast into another type of pointer to perform indirection. A null pointer is a pointer that does not point to an address. A void pointer can be a null pointer.
A void pointer is a pointer that has no associated data type with it. A void pointer can hold address of any type and can be typecasted to any type.
Explanation: Because the void pointer is used to cast the variables only, So pointer arithmetic can't be done in a void pointer.
The only limitations with void pointers are: you cannot dereference void pointer for obvious reasons. sizeof(void) is illegal. you cannot perform pointer arithmetics on void pointers.
Yes, it's legal, because:
void*
and back again;l_func
is an object (a functor, with unspecified class type) — that's how lambdas are implemented, by standard mandate.The FAQ text you cite is unrelated, as it refers to pointers to functions. _yourUnspecifiedLambdaType::operator()
is the equivalent* function, but you're not doing anything with that here.
* Well, it's not even equivalent, because it's a member function!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With