std :: async和std ::包装rvalue参考lambda时的差异
Difference between std::async and std::bind when wrapping rvalue reference lambda
受此评论的启发,该评论直接与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::bind
将message
保留为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。
相关文章:
- 可组合的lambda/std::函数与std::可选
- 将带有unique_ptr的可变 lambda 传递给 const&std::function
- 捕获lambda中的std::数组
- 如何调用存储在指向"std::函数"的指针中的 lambda?
- 如果模板没有可变参数,则 Lambda 被推导出为 std::function
- 为什么我不能在 constexpr lambda 函数中使用 std::tuple
- 从具有按值捕获的 lambda 移动构造 std::函数时,移动构造函数调用两次
- 将 lambda 表达式传递给 std::function in C++
- 在 lambda 表达式中使用 std::atomic
- 修改在 std::future 的 lambda 中引用捕获的值
- 在 lambda 中锁定 std::shared_ptr 的复制操作
- std::move a const std::vector in a lambda capture
- 从 std::function in C++ 访问模板化 lambda
- 如果 lambda 没有指定的类型,std::function 如何接受 lambda?
- 如何制作可以接受任何类型的参数的 std::函数和 lambda
- 是否可以将具有不同签名的 lambda 存储在 std::vector 中并在函数中执行它们(使用各自的参数)?
- 如何使用lambda作为std::unique_ptr的删除器?
- 创建一个带有 lambda 的 std::函数,而不知道函数的参数
- 针对 std::function 的 lambda 表达式和模板推导:为什么会这样?
- std::function<std::optional<T>()> 如何与返回 T 的 lambda 兼容?