Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why this lambda function in loop didn't capture the parameter by value?

Tags:

c++

c++11

lambda

I have following block of code, what I expected is the i inside the lambda capture list is passed by value and the i be outputted should be different.

However, the actual result is the output 20 lines of 19 is completed.

I tried to change the this line std::thread t([&func](){ to std::thread t([func](){, the output could print different i value.

My question is why std::thread t([&func](){ and std::thread t([func](){ will lead the different output value of i?

void DoSomething(std::function<void()> func)
{
    std::thread t([&func](){
        //do something
        sleep(1);
        if (func)
            func();
    });
    t.detach();
}

int main(int argc, const char * argv[]) {
    std::mutex mtx;
    for (int i = 1 ; i < 20; i ++) {
        DoSomething([i, &mtx](){
            std::unique_lock<std::mutex> lock(mtx);
            std::cout << i << " is completed" << std::endl;;
        });
    }
    sleep(10);
}
like image 906
2power10 Avatar asked Dec 05 '25 07:12

2power10


1 Answers

You're capturing a reference to DoSomething's parameter, func.
By the time your thread executes, that parameter's lifetime has ended so you have a dangling reference and using it is undefined.

like image 108
molbdnilo Avatar answered Dec 06 '25 23:12

molbdnilo