std :: async和std ::包装rvalue参考lambda时的差异

Difference between std::async and std::bind when wrapping rvalue reference lambda

本文关键字:std lambda rvalue async 包装 参考      更新时间:2023-10-16

受此评论的启发,该评论直接与rvalue参考参数直接与 std::async结合,将rvalue通过 std::async绑定到lambda,并按预期汇编并执行:(实时示例)

) ) ) >
auto lambda = [] (std::string&& message) {
    std::cout << message << std::endl;
};
auto future = std::async(lambda, std::string{"hello world"});
future.get();

使用std::bind,但是,触发编译器错误:(实时示例)

auto lambda = [] (std::string&& message) {
    std::cout << message << std::endl;
};
auto bound = std::bind(lambda, std::string{"hello world"}); // Compiler error
bound();

这是因为std::bindmessage保留为LVALUE,因此当它传递给lambda时,该参数不再匹配参数。

我已经读到std::async在内部使用std::bind,那么当std::bind没有时,它如何使用RVALUE参考参数呢?标准的特定部分需要此行为,还是取决于编译器?

我已经读过 std::async内部使用std::bind,那么它如何摆脱 当std::bind不进行rvalue参数?

它不内部使用bind。(或更确切地说,它不可能不经历 @praetorian的答案中的一些史诗般的扭曲,而单独写入一些东西也容易得多)。

通常使用某种 bind的机械实现,但要简单得多,因为它不必处理各种奇怪的东西 bind手柄(嵌套的 bind s,占位符,删除额外的参数,等等。)blockquote>

标准的特定部分需要此行为 还是这取决于编译器?

标准需要。bind的规范非常密集,但确实需要简单的绑定参数作为lvalues([func.bind.bind]/p10,bullet 4)。

async指定为调用INVOKE (DECAY_COPY (std::forward<F>(f)), DECAY_COPY (std::forward<Args>(args))...)DECAY_COPY始终返回rvalue。