So, there are a couple of problems with your code:
int x = 0;
this x
is never used. See below
[x = foo()]
This does not capture the variable x
in main
. Instead it is a generalized lambda capture. If you want to think in the terms of the class type equivalent of the lambda, it creates a member named x
initialized with foo()
. Again absolutely no connection with the variable x
in main.
[x = foo()]()mutable{ x = foo(); cout << "in un-named lambda x: " << x << endl; };
And finally your lambda is never called. So { x = foo(); cout << "in un-named lambda x: " << x << endl; }
is never executed.
There is this awesome tool which lets you see what transformation the compiler does to your code: https://cppinsights.io/s/cd26f632
#include <iostream>
int foo()
{
std::operator<<(std::cout, "foo()").operator<<(std::endl);
return 1024;
}
int main()
{
int x = 0;
class __lambda_12_5
{
int x;
public:
inline /*constexpr */ void operator()()
{
x = foo();
std::operator<<(std::cout, "in un-named lambda x: ").operator<<(x).operator<<(std::endl);
}
public: __lambda_12_5(int _x)
: x{_x}
{}
} __lambda_12_5{foo()};
;
}
Also please enable and heed your warnings: Why should I always enable compiler warnings?
source>:12:5: warning: expression result unused [-Wunused-value]
[x = foo()]()mutable{ x = foo(); std::cout << "in un-named lambda x: " << x > << std::endl; };
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~> ~~~~~~~~~~
<source>:11:9: warning: unused variable 'x' [-Wunused-variable]
int x = 0;
^
2 warnings generated.
As you see you are told about both of the unused variable and the not called lambda.