vault backup: 2022-06-13 17:44:14
Affected files: 02. PARA/03. Resources(資源)/C++17/lambda.md
This commit is contained in:
@@ -27,8 +27,8 @@ auto comapre = [] (int x, int y) -> bool {
|
||||
|
||||
## Lamdba的擷取子句
|
||||
以中括號開頭的 *lamdba 導入器*可以將外部的變數傳給 Lamdba 運算式,正式名稱是「擷取子句(capture clause)」。
|
||||
`[=]` 表示它們會以值擷取(captured by value)。Scope內的變數都可以在
|
||||
`[&]` 表示它們會以址擷取(captured by reference)。
|
||||
`[=]` 表示它們會以值擷取(captured by value)。Scope內的變數可以在 lamdba 內使用,但是不可以改變。
|
||||
`[&]` 表示它們會以址擷取(captured by reference)。Scope內的變數可以在 lamdba 內使用,可以改變。
|
||||
|
||||
### 以值擷取(captured by value)
|
||||
假設有一段程式如下:
|
||||
@@ -72,6 +72,49 @@ auto findInRange = [=](int32_t start, int32_t end) mutable { // <-- assign mutab
|
||||
};
|
||||
```
|
||||
|
||||
####
|
||||
根據書上解釋 ,可以裡解為 compiler 會將 lamdba 編為一個 class,像是:
|
||||
```cpp
|
||||
class __Lambda8C1A5 {
|
||||
public:
|
||||
__Lambda8C1A5(const std::vector<int32_t>& arg1) : numlist(arg1) {}
|
||||
auto operator()(int32_t start, int32_t end) const { // const!
|
||||
for (auto num : numlist) {
|
||||
if (num >= start && num <= end) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private:
|
||||
std::vector<int32_t> numlist;
|
||||
};
|
||||
```
|
||||
|
||||
這也解釋了 lamdba 的擷取範圍與原理。而 `mutable` 則是讓 `operator()` 不為 `const`,如下:
|
||||
```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;
|
||||
};
|
||||
|
||||
...
|
||||
|
||||
class __Lambda8C1A5 {
|
||||
public:
|
||||
__Lambda8C1A5(const std::vector<int32_t>& arg1) : numlist(arg1) {}
|
||||
auto operator()(int32_t start, int32_t end) { // No const here
|
||||
for (auto num : numlist) {
|
||||
if (num >= start && num <= end) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private:
|
||||
std::vector<int32_t> numlist;
|
||||
};
|
||||
```
|
||||
|
||||
### 以址擷取(captured by reference)
|
||||
Reference in New Issue
Block a user