public member function
<future>

std::packaged_task::valid

bool valid() const noexcept;
Check for valid shared state
Returns whether the packaged_task is currently associated with a shared state.

For default-constructed packaged_task objects, this function returns false (unless move-assigned or swapped with a valid packaged_task).

Parameters

none

Return value

true if the object is associated with a shared state.
false otherwise.

Data races

The packaged_task object is accessed.

Example

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

// function that launches an int(int) packaged_task in a new thread:
std::future<int> launcher (std::packaged_task<int(int)>& tsk, int arg) {
	if (tsk.valid()) {
      std::future<int> ret = tsk.get_future();
	  std::thread (std::move(tsk),arg).detach();
	  return ret;
	}
	else return std::future<int>();
}

int main ()
{
  std::packaged_task<int(int)> tsk ([](int x){return x*2;});

  std::future<int> fut = launcher (tsk,25);

  std::cout << "The double of 25 is " << fut.get() << ".\n";

  return 0;
}

Output:

The double of 25 is 50.


Exception safety

No-throw guarantee: never throws exceptions.

See also