CKTIS / C++
std::shared_future — shared access to a result
std::shared_future lets multiple consumers access one result or exception. It is copyable and supports repeated get() calls; wait() waits for readiness, while wait_for() checks readiness with a timeout.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <chrono>
#include <future>
std::shared_future<T> sf = future.share();
const T& value = sf.get(); // primary template
sf.wait();
std::future_status status = sf.wait_for(std::chrono::milliseconds{0});std::shared_future<T> from <future> is a copyable handle to shared state containing a result or exception. Copies refer to the same state, not copies of the result. future.share() transfers the state from std::future<T> into std::shared_future<T>; the source object then has valid() == false.
std::shared_future::get() waits for readiness and returns const T&; for std::shared_future<T&> it returns T&, and for std::shared_future<void> it returns no value. It throws the stored exception, if any. Unlike std::future::get(), it does not consume the state: repeated calls are allowed. A reference to the stored value must not be used after the shared state is destroyed; the reference specialization does not extend the referred object's lifetime.
std::shared_future::wait() waits for readiness without retrieving the result or throwing the stored exception. std::shared_future::wait_for(duration) returns std::future_status::ready, std::future_status::timeout, or std::future_status::deferred. For a deferred task it returns deferred without starting it; wait() or get() may execute it. A timeout neither cancels work nor provides a strict return-time guarantee.
These three operations require valid() == true; violating this condition causes undefined behavior, not a guaranteed exception. Use separate handle copies in different threads. Readiness synchronizes publication of the result, but subsequent concurrent data modifications require their own synchronization. The example intentionally uses one thread: it demonstrates shared state and repeated reads without scheduling dependencies.
Examples
#include <chrono>
#include <future>
#include <iostream>
int main() {
std::promise<int> producer;
std::shared_future<int> first = producer.get_future().share();
auto second = first;
const auto before = first.wait_for(std::chrono::milliseconds{0});
producer.set_value(42);
second.wait();
const auto after = second.wait_for(std::chrono::milliseconds{0});
std::cout << std::boolalpha;
std::cout << "timeout: " << (before == std::future_status::timeout) << '\n';
std::cout << "ready: " << (after == std::future_status::ready) << '\n';
std::cout << first.get() << ' ' << second.get() << ' ' << first.get() << '\n';
}
Result
timeout: true ready: true 42 42 42
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.