c++ - Lambda 函数捕获变量与返回值?

标签 c++ c++11 lambda

我正在学习 C++11 新函数 lambda 函数,有点困惑。 我看过了

 []         Capture nothing (or, a scorched earth strategy?)
 [&]        Capture any referenced variable by reference
 [=]        Capture any referenced variable by making a copy
 [=, &foo]  Capture any referenced variable by making a copy, but capture variable foo by reference
 [bar]      Capture bar by making a copy; don't copy anything else
 [this]     Capture the this pointer of the enclosing class

我的问题是捕获变量到底是什么意思,返回值有什么区别,如果你想捕获一个变量,你必须正确地返回它?

例如:

[] () { int a = 2; return a; } 

为什么不是

int [] () { int a = 2; return a; }

最佳答案

您可以“捕获”属于封闭函数的变量。

void f() {
    int a=1;
    // This lambda is constructed with a copy of a, at value 1.
    auto l1 = [a] { return a; };
    // This lambda contains a reference to a, so its a is the same as f's.
    auto l2 = [&a] { return a; };

    a = 2;

    std::cout << l1() << "\n"; // prints 1
    std::cout << l2() << "\n"; // prints 2
}

如果需要,您可以返回捕获的变量,也可以返回其他内容。返回值与捕获无关。

关于c++ - Lambda 函数捕获变量与返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38835154/

相关文章:

c++ - 我什么时候应该使用 std::async with sync 作为策略?

c++ - 在 lambda 中捕获所有内容与仅捕获一些内容

c++ - rapidjson writer 生成额外的大括号

c++ - 如何编写一个简单的调试器?

c++ - 使用 "yes","no","i","out"作为变量/枚举的名称是否安全?

c++ - 为什么 std::result_of<int(int)>::type 无效?

c++ - 使数学 vector 类成为初始化列表感知

Python类: Lambda Name Error - Name not defined

java - 在 Java 8 中使用收集器的简单示例

c++ - 将简单网格加载到 OpenGL 时遇到问题