-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLambdaThisByValue.cpp
68 lines (53 loc) · 1.36 KB
/
LambdaThisByValue.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/**
* \file main.cpp
* \brief 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.
*/
#include <StdStream/StdStream.h>
#include <StdTest/StdTest.h>
#include <Stl.h>
//-------------------------------------------------------------------------------------------------
struct A
{
int value {123};
auto valueCopy() const
{
STD_TRACE_FUNC;
return
[*this]() -> int
{
return value;
};
}
auto valueRef() const
{
STD_TRACE_FUNC;
return
[this]() -> int
{
return value;
};
}
};
//-------------------------------------------------------------------------------------------------
int main(int, char **)
{
A a;
const auto funcCopy = a.valueCopy();
const auto funceRef = a.valueRef();
a.value = 321;
std::cout << STD_TRACE_VAR(funcCopy()) << std::endl;
std::cout << STD_TRACE_VAR(funceRef()) << std::endl;
return EXIT_SUCCESS;
}
//-------------------------------------------------------------------------------------------------
#if OUTPUT
::: valueCopy :::
::: valueRef :::
funcCopy(): 123
funceRef(): 321
#endif