CKTIS / C++
std::future: one-shot asynchronous result
std::future is a movable, non-copyable handle to one shared state containing either a value or an exception.
Version: C++23
Syntax
template<class R> class std::future {
public:
future() noexcept;
future(future&&) noexcept;
future(const future&) = delete;
R get();
bool valid() const noexcept;
void wait() const;
template<class Rep, class Period>
std::future_status wait_for(const std::chrono::duration<Rep, Period>& timeout) const;
std::shared_future<R> share() noexcept;
};std::future<R> from <future> represents the exclusive receiving end of shared state created by std::promise, std::packaged_task, or std::async. wait() blocks until ready, while wait_for and wait_until report ready, timeout, or deferred. std::future::get waits and retrieves a moved value for future<R>, a reference for future<R&>, or nothing for future<void>. std::future::share transfers the state to a shared_future, and std::future::valid tests whether the handle still has a state.
The example obtains a future from std::promise<int>, starts a thread that stores 42, and calls result.get(). Setting the value makes the state ready and synchronizes the receiver. get() returns 42 and then releases the state, so result.valid() is false. After join(), the program prints 42 0. The promise is captured by reference but remains alive until the thread has finished.
std::future is one-shot: after get(), share(), or a move, the source object has no state. Calling most members while valid() == false has undefined behavior; the standard recommends detecting it with std::future_error(no_state), but code cannot rely on that. get() rethrows an exception stored by the provider, while destruction of a std::promise without a result stores broken_promise. Use std::shared_future for multiple consumers. Member calls on the same future do not synchronize with one another, so do not operate concurrently on one object.
Examples
#include <future>
#include <iostream>
#include <thread>
int main() {
std::promise<int> promise;
std::future<int> result = promise.get_future();
std::thread producer([&promise] { promise.set_value(42); });
const int value = result.get();
producer.join();
std::cout << value << ' ' << result.valid() << '\n';
}
Result
42 0
std::future → 42 0