public member function
<future>

std::promise::get_future

future<T> get_future();
獲取 future
返回一個與物件的共享狀態關聯的future物件。

一旦就緒,返回的future物件就可以訪問由promise物件設定的值或異常。

每個promise共享狀態只能檢索一個future物件。

呼叫此函式後,promise應在某個時候使其共享狀態就緒(透過設定值或異常),否則在銷燬時會自動使其就緒,幷包含一個型別為future_error(具有broken_promise錯誤條件)的異常。

引數



返回值

一個引用了此promise相同共享狀態future物件。
T 是值(promise的模板引數)的型別。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// promise example
#include <iostream>       // std::cout
#include <functional>     // std::ref
#include <thread>         // std::thread
#include <future>         // std::promise, std::future

void print_int (std::future<int>& fut) {
  int x = fut.get();
  std::cout << "value: " << x << '\n';
}

int main ()
{
  std::promise<int> prom;                      // create promise

  std::future<int> fut = prom.get_future();    // engagement with future

  std::thread th1 (print_int, std::ref(fut));  // send future to new thread

  prom.set_value (10);                         // fulfill promise
                                               // (synchronizes with getting the future)
  th1.join();
  return 0;
}

輸出

value: 10


資料競爭

promise 物件被修改。

異常安全

基本保證:如果丟擲異常,則 promise 物件處於有效狀態。

此成員函式在以下條件下丟擲異常
異常型別錯誤條件描述
future_errorfuture_errc::no_state該物件沒有共享狀態(它已被移動賦值
future_errorfuture_errc::future_already_retrieved先前對該成員函式的呼叫已檢索到future
根據庫實現,此成員函式還可能丟擲異常來報告其他情況(例如bad_allocsystem_error)。

另見