这个函数和 lambda 有什么区别?
What's the difference between this function and the lambda?
#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 的方式与使用调用运算符调用函数的方式相同"。
相关文章:
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 在 .h 文件中的类中声明静态变量和在.cpp文件中声明"global"变量有什么区别
- 我是C++编程的新手,这些代码之间有什么区别,我应该使用哪一个
- 返回常量对象引用 (getter) 和仅返回字符串有什么区别?
- Qt:remove() 和 rmdir() 有什么区别
- 这 4 个 lambda 表达式之间有什么区别?
- 将向量作为类>(值)<向量启动和向量<类>[值]有什么区别
- typedef 枚举和枚举类有什么区别?
- &C::c 和 &(C::c) 有什么区别?
- ascii 和 unicode 在处理级别有什么区别吗?
- C 中的常量限定符和 C++ 中的常量限定符有什么区别?
- "ABC" 和 "ABC" ) 在C++中有什么区别?
- 空指针常量 (nullptr)、空指针值和空成员指针值之间有什么区别?
- 引用捕获和在 lambda 中通过引用发送参数有什么区别 (C++)
- 两种访问I2C总线的方法有什么区别?
- 两种模板示例有什么区别?
- 这两种C++语法之间有什么区别?
- lua 5.0.2 模块和 5.3.5 有什么区别?
- C++中"typedef"、"using"、"namespace"和"using namespace"有什么区别?
- std::enable_if 和 std::enable_if_t 有什么区别?