遵循 Kerrek 在什么是 std::promise 中的指南?. 我尝试了类似的示例代码,但没有达到我的预期。
也就是说,捕获的future_errc 错误的成员函数code() 与其what() 不匹配。准确地说,调用code()正确返回,what()返回code()下一位的信息。我怀疑这在 Visual Studio 2012 中有什么问题。
示例代码:
std::future<int> test_future_error1()
{
std::promise<int> prom;
std::future<int> fu = prom.get_future();
prom.set_value(5566);
return fu;
}
//---------------------------------------------------------------
std::future<int> test_future_error2()
{
std::promise<int> prom;
std::future<int> fu = prom.get_future();
std::future<int> fu2 = prom.get_future(); // throw std::future_errc::future_already_retrieved
prom.set_value(5566);
return fu;
}
//---------------------------------------------------------------
std::future<int> test_future_error3()
{
std::promise<int> prom;
std::future<int> fu = prom.get_future();
prom.set_value(5566);
prom.set_value(7788); // throw std::future_errc::promise_already_satisfied
return fu;
}
//---------------------------------------------------------------
std::future<int> test_future_error4()
{
std::promise<int> prom;
std::future<int> fu = prom.get_future();
return fu;
} // throw std::future_errc::broken_promise at fu.get()
//---------------------------------------------------------------
std::future<int> test_future_error5()
{
std::future<int> fu;
return fu;
} // throw std::future_errc::no_state at fu.get()
//---------------------------------------------------------------
int _tmain(int argc, _TCHAR* argv[])
{
try {
std::future<int> fu = test_future_error3();
int a = fu.get();
std::cout << "a= " << a << std::endl;
} catch(const std::future_error &e) {
std::cout << "future_error:" << std::endl;
if( e.code() == std::future_errc::broken_promise )
std::cout << "code() == std::future_errc::broken_promise" << std::endl;
else if( e.code() == std::future_errc::future_already_retrieved )
std::cout << "code() == std::future_errc::future_already_retrieved" << std::endl;
else if( e.code() == std::future_errc::promise_already_satisfied )
std::cout << "code() == std::future_errc::promise_already_satisfied" << std::endl;
else if( e.code() == std::future_errc::no_state )
std::cout << "code() == std::future_errc::no_state" << std::endl;
else
std::cout << "code() == unknown" << std::endl;
std::cout << "what() == " << e.what() << std::endl;
} catch(const std::exception &e) {
std::cout << "excepton: " << e.what() << std::endl;
}
std::system("pause");
return 0;
}
结果:
future_error:
code() == std::future_errc::promise_already_satisfied
what() == no state