std::future valid()
时间: 2024-01-22 10:02:10 浏览: 97
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.
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)