I wonder why I can use global variables (thanks to Chris Drew for correcting me) in lamdas and why I don't need to capture them:
#include <iostream>
#include <vector>
using namespace std;
size_t i = 0;
vector<int> v = {1,2,3};
int main()
{
auto lambda = [](){i = v.size();};
lambda();
cout << i << endl;
return EXIT_SUCCESS;
}
In this minimum working example I am accessing the size_t and the vector without capturing them. I would have to if they were declared inside the main-method. Why is that so and how can I copy the size_t and the vector? I tried to use [=]
as capture list but it does not copy v
and i
.