The following code block launches a thread via a lambda expression. This lambda expression captures a local variable "testVar" by reference. By the time the thread function executes that local variable goes out of scope and the thread function will not be able to access the correction values. Briefly tested capturing by copy by changing "&" to "=" in the capture clause. The for loop seems to print the correct values. My question is when does the capture happen? Does it happen when the lambda function is created or when the thread gets executed. In the latter case, capturing by copy should not produce the right results.
#include <iostream>
#include <string>
#include <vector>
#include <thread>
int main()
{
std::thread myThread;
{
std::vector<int> testVar(10, 128);
std::cout<<"Trying to create thread"<<std::endl;
myThread = std::thread([&](){std::this_thread::sleep_for(std::chrono::seconds(3));for(int i=0; i<10; i++){std::cout<<testVar[i]<<std::endl;}});
}
myThread.join();
}
Capturing by reference produces the following result
Trying to create thread 1580344384 21851 1580269584 21851 128 128 128 128 128 128
Capturing by copy produces the following result
Trying to create thread 128 128 128 128 128 128 128 128 128 128
auto lambda = [=](){for(auto x : testVar) std::cout<<x<<'\n';}; testVar = std::vector<int>(6, 32); lambda();
. What is the result? What does that tell you about when the capture is made? – Chemmy