std::future::get

来自cppreference.com
< cpp‎ | thread‎ | future
T get();
(1) (仅为泛型 future 模板的成员)
(C++11 起)
T& get();
(2) (仅为 future<T&> 模板特化的成员)
(C++11 起)
void get();
(3) (仅为 future<void> 模板特化的成员)
(C++11 起)

get 方法等待直至 future 拥有合法结果并(依赖于使用哪个模板)获取它。它等效地调用 wait() 等待结果。

泛型模板和二个模板特化各含单个 get 版本。 get 的三个版本仅在返回类型有别。

若调用此函数前 valid()false 则行为未定义。

释放任何共享状态。调用此方法后 valid()false

目录

[编辑] 参数

(无)

[编辑] 返回值

1) 存储于共享状态的值 v ,如同 std::move(v)
2) 存储于共享状态的值的引用。
3) 无。

[编辑] 异常

若 future 所引用的共享状态中存储异常(例如,通过调用 std::promise::set_exception() ),则抛出该异常。

[编辑] 注意

鼓励实现在调用前检测 valid()false 的情况,并抛出以 std::future_errc::no_state 为 error_condition 的 std::future_error

[编辑] 示例

#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

[编辑] 参阅

检查 future 是否拥有共享状态
(公开成员函数) [编辑]