2017-07-13 63 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临时对象在同一个完整表达式中以相反的构造顺序被破坏;除了由于被绑定到引用而延长了生命周期的那些。 (哪些不这样做)。 –