Inspired by this comment about binding lambdas with rvalue reference parameters directly to std::async
, binding an rvalue to a lambda through std::async
compiles and executes as expected: (live example)
auto lambda = [] (std::string&& message) {
std::cout << message << std::endl;
};
auto future = std::async(lambda, std::string{"hello world"});
future.get();
Using std::bind
, however, triggers a compiler error: (live example)
auto lambda = [] (std::string&& message) {
std::cout << message << std::endl;
};
auto bound = std::bind(lambda, std::string{"hello world"}); // Compiler error
bound();
This is because std::bind
keeps message
as an lvalue, so that when it passes it to the lambda, the argument no longer matches the parameter.
I've read that std::async
internally uses std::bind
, so how does it get away with rvalue reference parameters when std::bind
does not? Is there a particular part of the standard that requires this behavior or is this dependent on the compiler?