public member function
<future>

std::future::share

shared_future<T> share();
Get shared future
Returns a shared_future object that acquires the shared state of the future object.

The future object (*this) is left with no shared state (as if default-constructed) and is no longer valid.

Parameters

none

Return value

A shared_future object that acquires the shared state of *this, as if constructed as:
1
shared_future<T>(std::move(*this))
T is the type of the value (the template parameter of future).

Example

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;
}

Output:

value: 10
its double: 20


Data races

The future object is modified.

Exception safety

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).

See also