2017-07-13 67 views
3

在VS2015中的下面的代碼中,我在第一行得到acefbd,這是正確的。但是在第二次測試中,我將其分爲單獨的行,輸出爲abcdefVS2015 std ::異步奇怪

這是預期的行爲?

#include <future> 
#include <iostream> 

using namespace std; 

void a() { 
std::cout << "a"; 
std::this_thread::sleep_for (std::chrono::seconds (3)); 
std::cout << "b"; 
} 

void c() { 
std::cout << "c"; 
std::this_thread::sleep_for (std::chrono::seconds (4)); 
std::cout << "d"; 
} 

void e() { 
std::cout << "e"; 
std::this_thread::sleep_for (std::chrono::seconds (2)); 
std::cout << "f"; 
} 

int main() 
{ 
    std::async (std::launch::async, a), std::async (std::launch::async, c), std::async (std::launch::async, e); 

cout << "\n2nd Test" << endl; 

std::async (std::launch::async, a); 
std::async (std::launch::async, c); 
std::async (std::launch::async, e); 

} 

回答

7

這有什麼做與Visual Studio,但你與std::future對象std::async回報做什麼。

當一個std::future對象被銷燬時,the destructor在等待未來準備就緒時。

第一行會發生什麼情況是您創建了三個未來對象,並且在完整表達式的末尾(創建最後一個對象之後)期貨超出範圍並被銷燬。

在「第二次測試」中,您創建了一個未來,然後在繼續之前必須被破壞,然後創建另一個未來,在繼續之前必須被破壞,最後是第三個未來,這當然也必須被破壞。

如果保存期貨在臨時變量的第二次測試,你應該得到相同的行爲:

auto temp_a = std::async (std::launch::async, a); 
auto temp_c = std::async (std::launch::async, c); 
auto temp_e = std::async (std::launch::async, e); 
+0

你知道以何種順序臨時工被破壞?像是它的實現定義? – Rakete1111

+0

@ Rakete1111我假設你的意思是使用逗號表達式進行第一次測試?然後不,我不知道,也不是沒有看過規範。 –

+2

@ Rakete1111臨時對象在同一個完整表達式中以相反的構造順序被破壞;除了由於被綁定到引用而延長了生命週期的那些。 (哪些不這樣做)。 –