std::future::get
STD::未来:
T get( | (1) | (member only of generic future template)(since C++11) |
---|---|---|
T& get( | (2) | (member only of future<T&> template specialization)(since C++11) |
void get( | (3) | (member only of future<void> template specialization)(since C++11) |
大get
方法直到future
有一个有效的结果,%28取决于使用了哪个模板%29检索它。它有效地调用wait()
为了等待结果。
泛型模板和两个模板专门化分别包含get
.三种版本get
仅在返回类型上有所不同。
如果valid()
是false
在调用此函数之前。
任何共享状态都会被释放。valid()
是false
在调用此方法之后。
参数
%280%29
返回值
1%29值v
存储在共享状态中,如std::move(v)
...
2%29以共享状态作为值存储的引用。
3%29什么都没有。
例外
如果异常存储在将来的%28e.g引用的共享状态中。通过打电话到std::promise::set_exception()
%29,则将引发该异常。
注记
鼓励实现在下列情况下检测情况:valid()
是false
在呼叫前抛出一个std::future_error
错误条件为std::future_errc::no_state
...
例
二次
#include <thread>
#include <future>
#include <iostream>
#include <string>
#include <chrono>
std::string time() {
static auto start = std::chrono::steady_clock::now(
std::chrono::duration<double> d = std::chrono::steady_clock::now() - start;
return "[" + std::to_string(d.count()) + "s]";
}
int main() {
using namespace std::chrono_literals;
{
std::cout << time() << " launching thread\n";
std::future<int> f = std::async(std::launch::async, []{
std::this_thread::sleep_for(1s
return 7;
}
std::cout << time() << " waiting for the future, f.valid() == "
<< f.valid() << "\n";
int n = f.get(
std::cout << time() << " future.get() returned with " << n << ". f.valid() = "
<< f.valid() << '\n';
}
{
std::cout << time() << " launching thread\n";
std::future<int> f = std::async(std::launch::async, []{
std::this_thread::sleep_for(1s
return true ? throw std::runtime_error("7") : 7;
}
std::cout << time() << " waiting for the future, f.valid() == "
<< f.valid() << "\n";
try {
int n = f.get(
std::cout << time() << " future.get() returned with " << n
<< " f.valid() = " << f.valid() << '\n';
} catch(const std::exception& e) {
std::cout << time() << " caught exception " << e.what()
<< ", f.valid() == " << f.valid() << "\n";
}
}
}
二次
可能的产出:
二次
[0.000004s] launching thread
[0.000461s] waiting for the future, f.valid() == 1
[1.001156s] future.get() returned with 7. f.valid() = 0
[1.001192s] launching thread
[1.001275s] waiting for the future, f.valid() == 1
[2.002356s] caught exception 7, f.valid() == 0
二次
另见
valid | checks if the future has a shared state (public member function) |
---|
© cppreference.com
在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。