【发布时间】:2012-09-30 16:00:25
【问题描述】:
我对使用 C++11 lambda 时遇到的一些示例感到困惑。 例如:
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << []()->string{return "Hello World 1!";}() << endl;
[]{cout << "Hello World 2!" << endl;}();
string result = [](const string& str)->string {return "Hello World " + str;}("2!");
cout << "Result: " << result << endl;
result = [](const string& str){return "Hello World " + str;}("3!");
cout << "Result: " << result << endl;
string s;
[&s](){s = "Hello World 4!";}; // does not work
cout << s << endl;
[&s](){s = "Hello World 4!";}(); // works!
cout << s << endl;
return 0;
}
我无法弄清楚最后的括号在做什么。他们是否作为构造函数实例化了一个 lambda?鉴于 lambda 的模板是:
[capture_block](parameters) mutable exception_specification -> return_type {body}
让我感到困惑的是,这些实例需要这些括号才能工作。有人能解释一下为什么需要它们吗?
【问题讨论】:
-
这是一个光辉的例子,说明为什么 lambdas 是应该谨慎使用的东西。我必须阅读该代码大约 5 次才能理解全部意图。
-
@Richard:抱歉,不,不是。这是如何误用它们的主要例子。您通常不会以与创建它完全相同的表达式来调用它。
-
@leemes - 通常的 C 和 C++ hello world 程序远没有这段代码那么密集。
-
@Xeo 定义并立即使用 lambda 的一个有用示例是为 const 变量分配一个需要一些复杂初始化代码的值:
const int x = []{ some init code }();所以你不需要一个单独的函数来在其余生中使xconst。但是,我可能是错的(再次):) -
@leemes:我特别说过你通常不要立即调用它。 ;) 使用一次性函数初始化静态成员也是如此。
标签: c++ lambda c++11 parentheses