huu*_*huu 8 c++ lambda rvalue-reference stdbind c++11
受此评论的启发,关于将lambda与rvalue引用参数直接std::async绑定到,通过std::async编译将rvalue绑定到lambda 并按预期执行:( 实例)
auto lambda = [] (std::string&& message) {
std::cout << message << std::endl;
};
auto future = std::async(lambda, std::string{"hello world"});
future.get();
Run Code Online (Sandbox Code Playgroud)
std::bind但是,使用会触发编译器错误:( 实例)
auto lambda = [] (std::string&& message) {
std::cout << message << std::endl;
};
auto bound = std::bind(lambda, std::string{"hello world"}); // Compiler error
bound();
Run Code Online (Sandbox Code Playgroud)
这是因为std::bind保持message为左值,因此当它将它传递给lambda时,参数不再与参数匹配.
我已经阅读了std::async内部使用的内容std::bind,那么当std::bind它没有时,如何使用rvalue引用参数?是否存在需要此行为的标准的特定部分,或者这取决于编译器?
我读过
std::async内部使用, 那么当不使用std::bind右值引用参数时,它如何摆脱右值引用参数呢?std::bind
它不在bind内部使用。(或者更确切地说,它不可能不经历一些史诗般的扭曲,比如@Praetorian 在该问题中的回答,而且单独写一些东西要容易得多)。
它通常使用有点bind类似的机制来实现,但它要简单得多,因为它不必处理各种奇怪的事情bind句柄(嵌套bind、占位符、删除额外的参数等)
标准中是否有特定部分需要这种行为,或者这取决于编译器?
这是标准所要求的。的规范bind极其密集,但确实需要将普通绑定参数作为左值传递([func.bind.bind]/p10,项目符号 4)。
async被指定为 call INVOKE (DECAY_COPY (std::forward<F>(f)),
DECAY_COPY (std::forward<Args>(args))...),并且DECAY_COPY始终返回一个右值。