Can you reuse a std::future once it has already been assigned to std::async()?

I am curious if a std::future is instantiated and used to assign to the value of an std::async() operation, then waited for completion with .wait(), can it be re-assigned to a new async() operation?

Take this small code snippet for an example:

int fib(int n)
{
  if (n < 3) return 1;
  else return fib(n-1) + fib(n-2);
}

int main()
{
    std::future<int> f1 = std::async(std::launch::async, [](){
        return fib(40);
    });
 
    f1.wait();
    
    std::cout << "f1 first operation: " << f1.get() << '\n';

    f1 = std::async(std::launch::async, [](){
        return fib(43);
    });

    std::cout << "f1 second operation: " << f1.get() << '\n';
}

Are futures allowed to simply be re-assigned once they have been used once before?

I have not been able to find much reading material on this so far, and am interested if this is creating any undefined behavior for the future.

Any information is appreciated and thank you for the help!

>Solution :

Yes, it’s fine.

This is explicitly described in the documentation for operator=:

future& operator=( future&& other ) noexcept;

Releases any shared state and move-assigns the contents of other to *this. After the assignment, other.valid() == false and this->valid() will yield the same value as other.valid() before the assignment.

Leave a Reply