vault backup: 2022-06-13 17:34:14

Affected files:
02. PARA/03. Resources(資源)/C++17/lambda.md
This commit is contained in:
2022-06-13 17:34:14 +08:00
parent 2a75663f5f
commit 338e353f31

View File

@@ -27,7 +27,7 @@ auto comapre = [] (int x, int y) -> bool {
## Lamdba的擷取子句
以中括號開頭的 *lamdba 導入器*可以將外部的變數傳給 Lamdba 運算式正式名稱是「擷取子句capture clause」。
`[=]` 表示它們會以值擷取captured by value
`[=]` 表示它們會以值擷取captured by valueScope內的變數都可以在
`[&]` 表示它們會以址擷取captured by reference
### 以值擷取captured by value
@@ -47,7 +47,31 @@ void testLambda() {
}
```
`[=]`可以用來擷取 lamdba scope範圍所及的變數沒有在 Lamdba 運算式裡面被用到的變數舊部會被擷取,例如 `float notUsed = 1.0f;`
`[=]`可以用來擷取 lamdba scope範圍所及的變數沒有在 Lamdba 運算式裡面被用到的變數就不會被擷取,例如 `float notUsed = 1.0f;`
另一個重點是:**被擷取的變數是不可以更改的**。例如不能在lamdba裡面這樣寫
```cpp
auto findInRange = [=](int32_t start, int32_t end) {
numlist.push_back(5); // ERROR!
for (auto num : numlist) {
if (num >= start && num <= end) return true;
}
return false;
};
```
如果一定要在 lambda內改變擷取的變數那必須指名 lambda 為 `mutable`
```cpp
auto findInRange = [=](int32_t start, int32_t end) mutable { // <-- assign mutable
numlist.push_back(5);
for (auto num : numlist) {
if (num >= start && num <= end) return true;
}
return false;
};
```
####
### 以址擷取captured by reference