public member function
<future>

std::packaged_task::get_future

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

返回的future物件可以訪問packaged_task設定在共享狀態中的值或異常,一旦其儲存的任務呼叫

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

呼叫此函式後,packaged_task預計會在某個時候使其共享狀態準備就緒(透過呼叫其儲存的任務),否則在銷燬時會自動設定為就緒狀態,幷包含一個型別為future_error(錯誤條件為broken_promise)的異常。

引數



返回值

一個引用了與此packaged_task相同共享狀態future物件。
Ret儲存的任務的返回型別(packaged_task的第一個模板引數)。

示例

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
// packaged_task::get_future
#include <iostream>     // std::cout
#include <utility>      // std::move
#include <future>       // std::packaged_task, std::future
#include <thread>       // std::thread

// a simple task:
int triple (int x) { return x*3; }

int main ()
{
  std::packaged_task<int(int)> tsk (triple); // package task

  std::future<int> fut = tsk.get_future();   // get future

  std::thread(std::move(tsk),33).detach();   // spawn thread and call task

  // ...

  int value = fut.get();                     // wait for the task to complete and get result

  std::cout << "The triple of 33 is " << value << ".\n";

  return 0;
}

輸出

The triple of 33 is 99.


資料競爭

packaged_task物件已被修改。

異常安全

基本保證:如果丟擲異常,*packaged_task*處於有效狀態。

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

另見