有没有办法知道未来是否会在get()
上出现?
说我有一些这样的东西:
#include <cstdlib>
#include <future>
#include <stdexcept>
#include <iostream>
int main() {
srand(time(0));
auto randomSuccess = [] {
if (rand() >= rand())
throw std::runtime_error("Random exception");
};
auto f = std::async(std::launch::deferred,randomSuccess);
f.wait();
// from here,the future is valid
std::cout << "Now future is " << (f.valid() ? "valid" : "not valid yet") << std::endl;
f.get(); // how to know if this will throw?
}
我只想“窥探”未来的内部状态,就像bool valid() const noexcept;
那样,通过保持未来不受干扰(函数为const),这就是为什么放置try/catch
块不是什么我想做。