Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::promise — delivering a value or exception

std::promise<T> stores a single result in shared state read through std::future<T>. The result can be a value or an exception; the promise object itself does not start a computation or thread.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <future>
std::promise<T> p;
std::future<T> f = p.get_future();
p.set_value(value); // success
// Alternatively: p.set_exception(exception_ptr);

std::promise<T> from <future> is the result-writing side, while std::future<T> is the receiving side. std::promise::get_future() returns an object associated with the same shared state and can be called only once for that state. A promise can be moved but not copied; it does not itself start a thread.

std::promise::set_value stores a value and makes the state ready. For std::promise<T&> it stores a reference, while std::promise<void> uses set_value() to signal completion without a value. Alternatively, std::promise::set_exception stores a non-null std::exception_ptr, for example from std::current_exception() inside catch. future.get() waits for readiness and retrieves the value or rethrows the stored exception. Storing the result synchronizes with the successful return from waiting on that state.

The result can be successfully set only once: another attempt throws std::future_error with std::future_errc::promise_already_satisfied. Repeating get_future() reports std::future_errc::future_already_retrieved; having no state, for example after a move, is the error condition std::future_errc::no_state. Destroying a promise with an unready state stores std::future_error with std::future_errc::broken_promise and unblocks the receiver.

Examples

#include <exception>
#include <future>
#include <iostream>
#include <stdexcept>

int main() {
    std::promise<int> success;
    auto value = success.get_future();
    success.set_value(42);
    std::cout << value.get() << '\n';

    std::promise<int> failure;
    auto error = failure.get_future();
    try {
        throw std::runtime_error("calculation failed");
    } catch (...) {
        failure.set_exception(std::current_exception());
    }

    try {
        std::cout << error.get() << '\n';
    } catch (const std::runtime_error& e) {
        std::cout << e.what() << '\n';
    }
}

Result

42
calculation failed

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources