From 338e353f31ab21c5c676ffc18a4c593d37ee5ce0 Mon Sep 17 00:00:00 2001 From: Awin Huang Date: Mon, 13 Jun 2022 17:34:14 +0800 Subject: [PATCH] vault backup: 2022-06-13 17:34:14 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Affected files: 02. PARA/03. Resources(資源)/C++17/lambda.md --- .../03. Resources(資源)/C++17/lambda.md | 28 +++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/02. PARA/03. Resources(資源)/C++17/lambda.md b/02. PARA/03. Resources(資源)/C++17/lambda.md index bc72cac..a86bd61 100644 --- a/02. PARA/03. Resources(資源)/C++17/lambda.md +++ b/02. PARA/03. Resources(資源)/C++17/lambda.md @@ -27,7 +27,7 @@ auto comapre = [] (int x, int y) -> bool { ## Lamdba的擷取子句 以中括號開頭的 *lamdba 導入器*可以將外部的變數傳給 Lamdba 運算式,正式名稱是「擷取子句(capture clause)」。 -`[=]` 表示它們會以值擷取(captured by value)。 +`[=]` 表示它們會以值擷取(captured by value)。Scope內的變數都可以在 `[&]` 表示它們會以址擷取(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) \ No newline at end of file