通過此comment啓發約直接結合與右值參考參數的lambda到std::async
,通過std::async
編譯一個rvalue結合的λ和按預期執行:(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::bind
將message
保留爲左值,以便當它傳遞給lambda時,參數不再匹配參數。
我已經read是std::async
內部使用std::bind
,所以它是如何逃脫右值引用參數時std::bind
不?有沒有需要這種行爲的標準的特定部分,或者是否依賴於編譯器?