From cd7fe4b95777d950244c15297bc36d8e324ec46b Mon Sep 17 00:00:00 2001 From: Awin Huang Date: Mon, 13 Jun 2022 17:44:14 +0800 Subject: [PATCH] vault backup: 2022-06-13 17:44: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 | 49 +++++++++++++++++-- 1 file changed, 46 insertions(+), 3 deletions(-) diff --git a/02. PARA/03. Resources(資源)/C++17/lambda.md b/02. PARA/03. Resources(資源)/C++17/lambda.md index a86bd61..9ced500 100644 --- a/02. PARA/03. Resources(資源)/C++17/lambda.md +++ b/02. PARA/03. Resources(資源)/C++17/lambda.md @@ -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& 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 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& 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 numlist; +}; +``` ### 以址擷取(captured by reference) \ No newline at end of file