mirror of
https://github.com/AnthonyCalandra/modern-cpp-features.git
synced 2025-12-17 18:14:36 +03:00
Lambda capture this by value.
This commit is contained in:
21
README.md
21
README.md
@@ -9,6 +9,7 @@ C++17 includes the following new language features:
|
|||||||
- [folding expressions](#folding-expressions)
|
- [folding expressions](#folding-expressions)
|
||||||
- [new rules for auto deduction from braced-init-list](#new-rules-for-auto-deduction-from-braced-init-list)
|
- [new rules for auto deduction from braced-init-list](#new-rules-for-auto-deduction-from-braced-init-list)
|
||||||
- [constexpr lambda](#constexpr-lambda)
|
- [constexpr lambda](#constexpr-lambda)
|
||||||
|
- [lambda capture this by value](#lambda-capture-this-by-value)
|
||||||
- [inline variables](#inline-variables)
|
- [inline variables](#inline-variables)
|
||||||
- [nested namespaces](#nested-namespaces)
|
- [nested namespaces](#nested-namespaces)
|
||||||
- [structured bindings](#structured-bindings)
|
- [structured bindings](#structured-bindings)
|
||||||
@@ -153,6 +154,26 @@ constexpr int addOne(int n) {
|
|||||||
static_assert(addOne(1) == 2);
|
static_assert(addOne(1) == 2);
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Lambda capture `this` by value
|
||||||
|
Capturing `this` in a lambda's environment was previously reference-only. An example of where this is problematic is asynchronous code using callbacks that require an object to be available, potentially past its lifetime. `*this` (C++17) will now make a copy of the current object, while `this` (C++11) continues to capture by reference.
|
||||||
|
```c++
|
||||||
|
struct MyObj {
|
||||||
|
int value{ 123 };
|
||||||
|
auto getValueCopy() {
|
||||||
|
return [*this] { return value; };
|
||||||
|
}
|
||||||
|
auto getValueRef() {
|
||||||
|
return [this] { return value; };
|
||||||
|
}
|
||||||
|
};
|
||||||
|
MyObj mo;
|
||||||
|
auto valueCopy = mo.getValueCopy();
|
||||||
|
auto valueRef = mo.getValueRef();
|
||||||
|
mo.value = 321;
|
||||||
|
valueCopy(); // 123
|
||||||
|
valueRef(); // 321
|
||||||
|
```
|
||||||
|
|
||||||
### Inline variables
|
### Inline variables
|
||||||
The inline specifier can be applied to variables as well as to functions. A variable declared inline has the same semantics as a function declared inline.
|
The inline specifier can be applied to variables as well as to functions. A variable declared inline has the same semantics as a function declared inline.
|
||||||
```c++
|
```c++
|
||||||
|
|||||||
Reference in New Issue
Block a user