diff --git a/02. PARA/03. Resources(資源)/C++17/lambda.md b/02. PARA/03. Resources(資源)/C++17/lambda.md index c6c68bb..1bd27ac 100644 --- a/02. PARA/03. Resources(資源)/C++17/lambda.md +++ b/02. PARA/03. Resources(資源)/C++17/lambda.md @@ -199,4 +199,24 @@ auto findInRange = [&, numlist](int32_t start, int32_t end) { 上面的例子中,`numlist` 會以值擷取,其他的外部變數則是參考擷取。 但是,如果已經使用了 `=` ,就不可以再以值擷取其他變數,像是 `[=, numlist]` 就是不合法的。 -反之,如果已經使用了 `&`,就不可以再參考擷取其他變數,像是 `[&, &var1]` 就是不合法的。 \ No newline at end of file +反之,如果已經使用了 `&`,就不可以再參考擷取其他變數,像是 `[&, &var1]` 就是不合法的。 + +### 存取 class +Lamdba 寫在 class 裡面的時候,不論「以值擷取」或是「以參考擷取」都沒辦法傳遞成員變數(member variable),只能傳遞 `this`,透過 `this` 來存取成員變數。例: +```cpp +class BigBuffer { +public: + void modify(int x, int y, ...) { + auto modifyBuffer = [this] () { // Use this + if (buffer) { // equal to this->buffer + // do something with buffer + } + }; + ... + } + +private: + uint32_t bufferSize = 0; + std::unique_ptr buffer = nullptr; +}; +``` \ No newline at end of file