Think about what would happen if he bound the bar by reference.
Then, every time you called std::async , each value you pass should last until the asynchronization is complete.
This will be a recipe for accidental memory corruption. Thus, std::async instead copies by default everything that you pass to it.
Then it runs the task on a copy of your input.
Being smart, it tells the code you call that the value is not constant by moving it to the code. And lvalue links cannot bind to relocated values.
You can override this behavior using std::reference_wrapper . async understands reference_wrapper , and it automatically saves a link to these values ββand passes them by reference to the called code.
An easy way to create a reference_wrapper is to call std::ref .
int foo = 0; bool bar = false; std::future<std::string> async_request = std::async( std::launch::async, [=, &foo](bool& is_pumping_request) -> std::string { return "str"; }, std::ref(bar) ); std::cout << async_request.get() << std::endl;
and it just works.
This βonly pass by reference explicitlyβ is a security function of the binding operation as an operation; because linked execution can persist outside the current state, it requires callers to only link explicitly, thereby reducing the chance of inadvertent links to dangling links.
source share