1

If I capture a variable by reference in a lambda, and then pass that lambda by value to a new thread, I expected the variable to be copied (as part of the lambda), but that doesn't seem to be the case.

I expected the following code to print hello but it didn't. Can you explain why?

void foo(std::function<void()>& func)
{    
    std::thread t([func]() // capture func by value
    {
        Sleep(1000);
        func();
    });

    t.detach();
}

int main() 
{    
    {
        std::string str("hello");
        std::cout << "Main: Address of str is " << &str << std::endl;

        std::function<void()> func = [&str]()  // capture str by reference
        {
            std::cout << "Func: Address of str is " << &str << std::endl;
            std::cout << str << std::endl;
        };

        foo(func);
    }

    std::cin.get();
}
tcb
  • 4,408
  • 5
  • 34
  • 51

0 Answers0