Why cpp std::function can hold capture-lambda, while function pointer cannot?

Imm*_*ant 0 c++ lambda pointers function capture

I've got this code snippet:

    int x = 3;
    auto fauto = [=](){ cout<<'x'; };
    function<void()> func{fauto};
    func();
    void (*rawPf)() = fauto; // fail to compile
    rawPf();
Run Code Online (Sandbox Code Playgroud)

I knew the syntax that only non-capture lambda can be assigned to function pointer. But:

(1) Why std::function can hold capture-lambda?

(2) as both std::function and function pointers are callable, what's the core difference that makes std::function able to hold capture-lambda, while function pointer cannot?

Any detailed explanation on language design for this?

eng*_*010 6

为什么函数指针不能包含带有捕获的 lambda:因为 Lambda 不是函数,而是对象!

为什么没有捕获的 lambda 可以转换为函数指针?

Lambda 只是编译器生成的类的普通对象(一段数据)(具有只有编译器知道的唯一类名),具有编译器生成的函数运算符成员(即 auto operator() (???))使用您提供的参数定义(如果有)为您定义。lambda 对象的数据成员由捕获列表和/或其封闭范围的变量的使用来定义。

所有非静态成员函数在对象上调用时都会获得一个名为 this 的隐式隐藏参数。当您“调用” lambda 时也是如此。

现在,当你不捕获某些内容时,lambda 没有数据(空类),编译器不必为调用生成隐式 this 指针,这使得函数运算符就像普通函数一样,编译器可以将其转换为函数指针。所以不是 lambda 被转换为函数指针,而是 lambda 的函数运算符被转换。

为什么 std::function 可以同时容纳两者:因为它是一个模板,并且通过模板和专业化,您几乎可以做任何事情。