受此启发comment关于将带有右值引用参数的 lambda 直接绑定(bind)到 std::async
,通过 std::async
将右值绑定(bind)到 lambda 编译并按预期执行:(live example)
auto lambda = [] (std::string&& message) {
std::cout << message << std::endl;
};
auto future = std::async(lambda, std::string{"hello world"});
future.get();
但是,使用 std::bind
会触发编译器错误:( live example )
auto lambda = [] (std::string&& message) {
std::cout << message << std::endl;
};
auto bound = std::bind(lambda, std::string{"hello world"}); // Compiler error
bound();
这是因为 std::bind
将 message
保留为左值,因此当它传递给 lambda 时,参数不再与参数匹配。
我已经 read std::async
在内部使用 std::bind
,那么当 std::bind
不使用时它如何摆脱右值引用参数?标准中是否有特定部分需要这种行为,或者这取决于编译器?
最佳答案
I've read that
std::async
internally usesstd::bind
, so how does it get away with rvalue reference parameters whenstd::bind
does not?
它不使用 bind
在内部。 (或者更确切地说,它不可能不经历一些像 @Praetorian's answer in that question 中那样的史诗般的扭曲,而且单独写一些东西要容易得多)。
它通常使用某种 bind
来实现-就像机器一样,但它要简单得多,因为它不必处理各种奇怪的事情bind
句柄(嵌套 bind
s、占位符、删除额外参数等)
Is there a particular part of the standard that requires this behavior or is this dependent on the compiler?
这是标准所要求的。 bind
的规范非常密集,但确实需要将纯绑定(bind)参数作为左值传递([func.bind.bind]/p10,第 4 条)。
async
指定调用 INVOKE (DECAY_COPY (std::forward<F>(f)),
DECAY_COPY (std::forward<Args>(args))...)
, 和 DECAY_COPY
总是返回一个右值。
关于c++ - 包装右值引用 lambda 时 std::async 和 std::bind 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30085869/