Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't a lambda that captures variables by reference convertible to a function pointer?

If I have a lambda which captures all automatic variables by reference ([&] {}), why can't it be converted to a function pointer? A regular function can modify variables just like a lambda that captures everything by reference can, so why is it not the same?

I guess in other words, what is the functional difference between a lambda with a & capture list and a regular function such that the lambda is not convertible to a function pointer?

like image 907
template boy Avatar asked Nov 01 '14 19:11

template boy


2 Answers

So let's take the example of a trivial lambda:

Object o;
auto foo = [&]{ return o; };

What does the type of foo look like? It might look something like this:

struct __unique_unspecified_blah
{
    operator()() const {
        return o;
    }

    Object& o;
};

Can you create a function pointer to that operator()? No, you can't. That function needs some extra information that comes from its object. This is the same reason that you can't convert a typical class method to a raw function pointer (without the extra first argument where this goes). Supposing you did create some this pointer - how would it know where to get o from?

The "reference" part of the question is not relevant - if your lambda captures anything, then its operator() will need to reference some sort of storage in the object. If it needs storage, it can't convert to a raw function pointer.

like image 50
Barry Avatar answered Oct 15 '22 10:10

Barry


I guess in other words, what is the functional difference between a lambda with a & capture list and a regular function such that the lambda is not convertible to a function pointer?

References, though they aren't objects, need to be stored somewhere. A regular function cannot access local variables of another function; Only references (e.g. as parameters) that could refer to local variables. A Lambda with a & as the capture-default can, because every variable needed can be captured.
In other words: A regular function doesn't have state. A closure object with captured variables does have state. So a closure object cannot be reduced to a regular function, because the state would be lost.

like image 37
Columbo Avatar answered Oct 15 '22 11:10

Columbo