2015-05-06 36 views
8

通過此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::bindmessage保留爲左值,以便當它傳遞給lambda時,參數不再匹配參數。

我已經readstd::async內部使用std::bind,所以它是如何逃脫右值引用參數時std::bind不?有沒有需要這種行爲的標準的特定部分,或者是否依賴於編譯器?

回答

4

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的規範是可笑的密集的,但確實需要簡單的綁定參數作爲左值傳遞([func.bind.bind]/p10,第4項)。

async被指定爲呼叫INVOKE (DECAY_COPY (std::forward<F>(f)), DECAY_COPY (std::forward<Args>(args))...),並且DECAY_COPY總是返回一個右值。