为什么通过引用捕获变量的lambda不能转换为函数指针? [英] Why isn't a lambda that captures variables by reference convertible to a function pointer?

查看:354
本文介绍了为什么通过引用捕获变量的lambda不能转换为函数指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个lambda可以通过引用捕获所有自动变量( [&] {} ),为什么不能将其转换为函数指针?常规函数可以像通过引用捕获所有内容的lambda一样修改变量,所以为什么不一样呢?

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?

推荐答案

让我们以一个小小的lambda为例:

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

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

foo 的类型是什么样的?可能看起来像这样:

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

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

    Object& o;
};

是否可以创建指向该 operator()?不,你不能。该功能需要来自其对象的一些额外信息。这是您无法将典型的类方法转换为原始函数指针的原因(没有 this 所在的第一个自变量)。假设您确实创建了此指针-它如何知道从哪里获取 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?

引用问题的一部分不相关-如果您的lambda捕获了任何东西,则其 operator()将需要引用对象中的某种存储方式。如果需要存储,则无法转换为原始函数指针。

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.

这篇关于为什么通过引用捕获变量的lambda不能转换为函数指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆