c++ - 包装右值引用 lambda 时 std::async 和 std::bind 之间的区别

标签 c++ c++11 lambda rvalue-reference stdbind

受此启发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::bindmessage 保留为左值,因此当它传递给 lambda 时,参数不再与参数匹配。

我已经 read std::async 在内部使用 std::bind,那么当 std::bind 不使用时它如何摆脱右值引用参数?标准中是否有特定部分需要这种行为,或者这取决于编译器?

最佳答案

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?

它不使用 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/

相关文章:

c++ - 将此指针作为weak_ptr传递给内部类

c++ - 如何将 std::shared_ptr 添加到多个 STL 容器?

c# - 避免或接受中断编辑并继续的 C# 构造?

java - 如何使用 lambda 正确制作多级 map ?

C++,用一个字节存储两个变量

c++ - 您将如何在 GMP 中申报大量?

c++ - 多线程套接字超时?

c++ - 我可以在非标准容器上使用迭代器库的访问函数吗?

c# - Lambda表达式通过导航属性获取数据,LINQToEntities

c++ - 给定硬币的所有可能总和