[英]Lambda function capture a variable vs return value?
我正在學習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
}
您可以根據需要返回捕獲的變量,也可以返回其他內容。 返回值與捕獲無關。
捕獲列表用於將符號 帶入 lambda。 返回值是為了從 lambda返回值 。
同樣,lambda使用尾隨返回類型語法,例如[] () -> int { int a=2; return a; }
[] () -> int { int a=2; return a; }
[] () -> int { int a=2; return a; }
。 盡管通常最好隱式推導它
lambda函數的主要功能之一是它可以記住聲明它的作用域中的內容:
#include <iostream>
#include <vector>
#include <functional>
auto f(int i, int j) {
int k = i * j;
return [=](){ std::cout << k << "\n"; };
}
int main() {
std::vector<std::function<void(void)>> v;
v.push_back(f(2,2));
v.push_back(f(6, 7));
for (auto& l: v) {
l();
}
}
請注意,當我們調用lambda時,如何不必將其傳遞給任何東西?
Lambda本質上是函子對象周圍的語法糖,捕獲是將成員變量添加到函子的過程:
[](char* p){ *p = toupper(*p); }
struct Lambda1 {
int operator(char* p) const { *p = toupper(*p); }
};
int x = 42;
int y = 5;
[x, &y](int i){ return i * (x + y); }
struct Lambda2 {
int x_;
int& y_;
Lambda2(int x, int& y) : x_(x), y_(y) {}
int operator(int i) { return i*(x_ + y_); }
};
從lambda返回值是可選的,但返回值是lambda的輸出,而不是輸入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.