Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a void pointer point to a lambda function?

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?

like image 362
downhillFromHere Avatar asked Dec 14 '15 13:12

downhillFromHere


People also ask

Can void pointers point to anything?

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.

Can void pointer point to any type?

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.

What void pointer Cannot do?

Explanation: Because the void pointer is used to cast the variables only, So pointer arithmetic can't be done in a void pointer.

What is the limitation of 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.


1 Answers

Yes, it's legal, because:

  • pointers to objects may be cast to 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!

like image 120
Lightness Races in Orbit Avatar answered Sep 20 '22 15:09

Lightness Races in Orbit