【问题标题】:Difference between std::async and std::bind when wrapping rvalue reference lambda包装右值引用 lambda 时 std::async 和 std::bind 之间的区别
【发布时间】:2015-07-17 03:05:40
【问题描述】:

comment 的启发,关于将带有右值引用参数的 lambdas 直接绑定到 std::async,通过 std::async 将右值绑定到 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 不使用右值引用参数时,它如何摆脱呢?标准中是否有特定部分需要这种行为,或者这取决于编译器?

【问题讨论】:

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


    【解决方案1】:

    我有 read 那个 std::async 内部使用std::bind,那么它是如何逃脱的 std::bind 没有时引用参数的右值?

    它在内部不使用bind。 (或者更确切地说,它不能不经历一些史诗般的扭曲,比如@Praetorian's answer in that question 中的那种,单独写一些东西要容易得多)。

    它通常使用类似于bind 的机制来实现,但它更简单,因为它不必处理各种奇怪的事情bind 句柄(嵌套binds,占位符,删除额外的参数等)

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

    这是标准要求的。 bind 的规范非常密集,但确实需要将普通绑定参数作为左值传递([func.bind.bind]/p10,bullet 4)。

    async被指定调用INVOKE (DECAY_COPY (std::forward<F>(f)), DECAY_COPY (std::forward<Args>(args))...)DECAY_COPY总是返回一个右值。

    【讨论】:

      猜你喜欢
      • 2016-04-24
      • 2015-07-17
      • 1970-01-01
      • 1970-01-01
      • 2014-03-04
      • 2013-01-18
      • 2012-04-25
      • 2015-07-21
      • 2012-10-27
      相关资源
      最近更新 更多