Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading