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

你说的曾经没有我的故事 提交于 2019-12-04 08:52:29

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!