C++ Quiz165 of 173
Difficulty:
⬅️ Prev: 339Quiz ID: 340Next: 342 ➡️

According to the C++23 standard, what is the output of this program?

#include <future>
#include <iostream>

int main()
{
    try {
        std::promise<int> p;
        std::future<int> f1 = p.get_future();
        std::future<int> f2 = p.get_future();
        p.set_value(1);
        std::cout << f1.get() << f2.get();
    } catch(const std::exception& e)
    {
        std::cout << 2;
    }
}
Hint

Only in science fiction can one have multiple futures.

Reveal answer

2

Explanation

You can only get a future from a promise once. Trying to get it again throws future_error.

§[futures.promise]¶15:

future<R> get_future();

Throws: future_error if *this has no shared state or if get_future has already been called on a promise with the same shared state as *this.

*this of course has the same shared state as itself, so the second time we call get_future, an exception of type future_error is thrown. This exception is then caught, and we print 2.

⬅️ Prev: 339Quiz ID: 340Next: 342 ➡️