forked from PhysicsX/ExampleCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambdaOutOfScope.cpp
More file actions
36 lines (30 loc) · 799 Bytes
/
lambdaOutOfScope.cpp
File metadata and controls
36 lines (30 loc) · 799 Bytes
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
#include <iostream>
#include <string>
#include <functional>
// Example of passing this to lambda expression
// that is not working for out of scope case for
// dummy foo object
// should be used *this. It is available after c++17
// note: with this (without *this) example will NOT work with x86-64 gcc 11.2
// but it will work with x86-64 clang 13.0.0
struct foo
{
int id;
std::string name;
//std::function<void(void)> run()
auto run()
{
return[this]{ std::cout << id << ' ' << name << '\n'; };
//return[*this]{ std::cout << id << ' ' << name << '\n'; };
}
};
//std::function<void(void)> boo()
auto boo()
{
return foo{ 42, "john" }.run();
}
int main()
{
auto l = boo();
l(); // does not print 42 john
}