public member function
<future>

std::future::share

shared_future<T> share();
獲取共享 future
返回一個 shared_future 物件,該物件獲取 future 物件的*共享狀態*。

future 物件(*this)將不再擁有*共享狀態*(如同*預設構造*一樣),並且不再*有效*。

引數



返回值

一個 shared_future 物件,它獲取 `*this` 的*共享狀態*,如同構造為
1
shared_future<T>(std::move(*this))
T 是值型別(future 的模板引數)。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// future::share
#include <iostream>       // std::cout
#include <future>         // std::async, std::future, std::shared_future

int get_value() { return 10; }

int main ()
{
  std::future<int> fut = std::async (get_value);
  std::shared_future<int> shfut = fut.share();

  // shared futures can be accessed multiple times:
  std::cout << "value: " << shfut.get() << '\n';
  std::cout << "its double: " << shfut.get()*2 << '\n';

  return 0;
}

輸出

value: 10
its double: 20


資料競爭

future 物件將被修改。

異常安全

在*無效*的 future 物件上呼叫此成員函式,會產生*未定義行為*(儘管庫實現可能會檢測到此情況並丟擲具有 no_state *錯誤條件*的 future_error)。

另見