这个函数和 lambda 有什么区别?

What's the difference between this function and the lambda?

本文关键字:什么 区别 lambda 函数      更新时间:2023-10-16
#include<iostream>
using namespace std;
int* New()
{
    return new int(666);
}
int Foo()
{
    //method1:
    int* it = New();
    return *it;
    //method2:
    return []() { return *(new int(666)); };//Complier has a complain here
    /*Both New() and Lambda are callable object, are there any differences between method1 and method2?*/ 
}
int main()
{
    cout << Foo() << endl;
    return 0;
}

我刚C++,遇到了上面的情况,我回顾了 C++ Primer 的第 10.3.2 到 10.3.3 章,其中介绍了 lambda 表达式。但它对我不起作用,我也对我列出的最后一个注释感到困惑。

return []() { return *(new int(666)); };

此行试图返回 lambda 本身。 您想调用 lambda 并返回它生成的整数:

return []() { return *(new int(666)); }();  // Note the () at the end

不过,定义一个 lambda 函数只是为了立即调用它通常没有多大意义。 当您需要实际返回函数或将函数作为参数时,它们更常用。 (不过,这是一个更高级的事情,所以你现在可能不应该担心它。


另外一点:您的程序使用 new 分配整数,但它永远不会使用 delete 释放它们。 这是内存泄漏,这是您应该避免的。

实际上,我没有调用我的lambda,因为它缺少调用运算符。因此,我将其修复为:

return []() { return *(new int(666)); }();

它现在有效。

我回顾了C++入门 10.3.2 章中的单词"我们调用 lambda 的方式与使用调用运算符调用函数的方式相同"。