[英]Difference between std::async and std::bind when wrapping rvalue reference lambda
受到此評論的啟發,該評論涉及將帶有rvalue參考參數的lambda直接綁定到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();
但是,使用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
保留為左值,因此當將其傳遞給lambda時,參數不再與參數匹配。
我已經讀過 std::async
內部使用std::bind
,所以當std::bind
不這樣做時,它如何與右值引用參數區分開? 標准的特定部分是否需要這種行為,或者這取決於編譯器?
我已經讀過
std::async
內部使用std::bind
,所以當std::bind
不這樣做時,它如何與右值引用參數區分開?
它在內部不使用bind
。 (或者更確切地說,它不能不經歷一些史詩般的扭曲,例如該問題中@Praetorian的回答中的扭曲,而單獨寫一些東西要容易得多)。
它通常是用一個有些實施bind
式的機器,但它的簡單得多,因為它不具備處理的奇怪的事情各種各樣bind
句柄(嵌套bind
S,占位符,下探額外的參數等)
標准的特定部分是否需要這種行為,或者這取決於編譯器?
它是標准要求的。 bind
的規范非常荒謬,但是確實需要將純綁定參數作為左值傳遞([func.bind.bind] / p10,項目符號4)。
指定了async
來調用INVOKE (DECAY_COPY (std::forward<F>(f)), DECAY_COPY (std::forward<Args>(args))...)
,並且DECAY_COPY
始終返回右值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.