public member function
<future>

std::future::get

generic template (1)
T get();
reference specialization (2)
R& future<R&>::get();       // when T is a reference type (R&)
void specialization (3)
void future<void>::get();   // when T is void
Get value
Returns the value stored in the shared state (or throws its exception) when the shared state is ready.

如果*共享状态*尚未就绪(即提供者尚未设置其值或异常),则函数会阻塞调用线程,并等待其就绪。

Once the shared state is ready, the function unblocks and returns (or throws) releasing its shared state. This makes the future object no longer valid: this member function shall be called once at most for every future shared state.

All visible side effects are synchronized between the point the provider makes the shared state ready and the return of this function.

The member of the void specialization (3) does not return any value, but still waits for the shared state to become ready and releases it.

参数



返回值

Generally (1), std::move(x), where x is the value stored in the shared state.
For references (2), a reference to the value stored in the shared state.
For void futures (3), nothing.

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// future::get
#include <iostream>       // std::cout, std::ios
#include <future>         // std::async, std::future
#include <exception>      // std::exception

int get_int() {
  std::cin.exceptions (std::ios::failbit);   // throw on failbit set
  int x;
  std::cin >> x;                             // sets failbit if invalid
  return x;
}

int main ()
{
  std::future<int> fut = std::async (get_int);

  std::cout << "Please, enter an integer value: ";

  try {
    int x = fut.get();
    std::cout << "You entered: " << x << '\n';
  }
  catch (std::exception&) {
    std::cout << "[exception caught]";
  }

  return 0;
}

可能的输出

Please, enter an integer value: 101
You entered: 101


数据竞争

The future object is modified.
共享状态 作为 原子操作 被访问(不会导致数据竞争)。

异常安全

The function throws the exception stored in the shared state when the provider makes it ready by setting it to an exception. Note that in this case a basic guarantee is offered, with the future object being modified to no longer be a valid future (which is itself a valid state for object of this type, despite its name).

Calling this member function on a future object that is not valid, produces undefined behavior (although library implementations may detect this and throw future_error with a no_state error condition).

另见