std::future valid()
时间: 2024-01-22 20:02:10 浏览: 27
The std::future valid() function is used to check if a std::future object is valid, i.e., if it is associated with any shared state. The function returns true if the std::future object is valid and false otherwise.
Here's an example:
```
#include <iostream>
#include <future>
int main() {
std::future<int> fut;
std::cout << "Is future valid? " << fut.valid() << std::endl;
fut = std::async(std::launch::async, [](){ return 42; });
std::cout << "Is future valid? " << fut.valid() << std::endl;
int result = fut.get();
std::cout << "Result: " << result << std::endl;
std::cout << "Is future valid? " << fut.valid() << std::endl;
return 0;
}
```
Output:
```
Is future valid? 0
Is future valid? 1
Result: 42
Is future valid? 0
```
In this example, we create a std::future object `fut` and check if it is valid using the `valid()` function, which returns false as `fut` is not associated with any shared state.
Next, we create a task using `std::async()` and assign the returned future object to `fut`. We then check if `fut` is valid using the `valid()` function, which returns true as `fut` is now associated with a shared state.
We then call `fut.get()` to retrieve the result of the task and store it in `result`. After that, we check if `fut` is still valid using the `valid()` function, which now returns false as the shared state has been consumed.