Demystifying std::future_error::code in C++ Concurrency

2025-09-03

In C++ concurrency, when you're using futures (like std::future), they provide a way to get the result of an asynchronous operation. The std::future_error is an exception that's thrown when something goes wrong with a future. The std::future_error::code tells you exactly what went wrong. Think of it as a specific error message for your future.

The most common error codes you'll see are

std::future_errc::future_already_retrieved
This is probably the most frequent error. It means you tried to get the result from a future that has already had its result retrieved. A std::future can only have its value "gotten" once.

std::future_errc::promise_already_satisfied
This happens when you try to set a value or an exception on a std::promise that has already had its value or exception set. A promise can only be fulfilled once.

std::future_errc::no_state
This indicates that the std::future you're trying to use is empty or has no shared state. This often happens if you move the future to another variable or if it was created without a valid promise.

Let's look at some common scenarios where these errors pop up and how you can fix them.

This error often occurs in scenarios where multiple parts of your code might try to access the same future.

Problematic Code

#include <iostream>
#include <future>

int main() {
    std::promise<int> p;
    std::future<int> f = p.get_future();

    // In a real application, another thread would fulfill the promise
    p.set_value(42); 

    // This first call is fine
    int result1 = f.get(); 
    std::cout << "Result 1: " << result1 << std::endl;

    //  This will throw std::future_error with future_already_retrieved
    try {
        int result2 = f.get(); 
    } catch (const std::future_error& e) {
        std::cout << "Caught exception: " << e.what() << " (code: " << static_cast<int>(e.code().value()) << ")" << std::endl;
    }

    return 0;
}

Solution / Alternative

If you need to access the value multiple times, you should get the value once and store it. Or, if you have multiple consumers, consider using a std::shared_future. A std::shared_future allows multiple threads to wait for and retrieve the same result.

Sample Code using std::shared_future

#include <iostream>
#include <future>

int main() {
    std::promise<int> p;
    // Use std::shared_future
    std::shared_future<int> sf = p.get_future().share(); 

    // Another thread would run this
    p.set_value(42); 

    // Now, multiple calls to .get() are allowed
    int result1 = sf.get(); 
    std::cout << "Result 1: " << result1 << std::endl;

    int result2 = sf.get(); 
    std::cout << "Result 2: " << result2 << std::endl;

    return 0;
}

This happens when a future is "empty," often because its state has been moved away. std::future is a move-only type, meaning it cannot be copied.

Problematic Code

#include <iostream>
#include <future>

std::future<int> get_future_from_somewhere() {
    std::promise<int> p;
    // This returns a temporary future
    return p.get_future(); 
    //  The promise 'p' is destroyed here, and the shared state is lost. 
    // The returned future is now "empty"
}

int main() {
    std::future<int> f = get_future_from_somewhere();

    try {
        //  This will throw std::future_error with no_state
        int result = f.get();
    } catch (const std::future_error& e) {
        std::cout << "Caught exception: " << e.what() << " (code: " << static_cast<int>(e.code().value()) << ")" << std::endl;
    }

    return 0;
}

Solution / Alternative

Ensure that the promise and the future's shared state live long enough for the future to be used. One way to handle this is to have a class or a longer-lived object manage the promise and future, or to pass the future by value to a function that needs it.

Sample Code with Correct State Management

#include <iostream>
#include <future>
#include <thread>

int compute_value(std::promise<int>&& p) {
    // Fulfill the promise within the thread
    p.set_value(123); 
    return 123;
}

int main() {
    std::promise<int> p;
    std::future<int> f = p.get_future();

    // Pass the promise to a thread
    std::thread t(compute_value, std::move(p));

    // Wait for the result
    int result = f.get(); 
    std::cout << "Result: " << result << std::endl;

    t.join();

    return 0;
}

In this correct example, the std::promise is moved to the thread, so its state remains valid until it's fulfilled, and the std::future can retrieve the value successfully.


cpp



Safe and Clean Operator Overloading for std::variant in C++

In C++, std::variant is a type-safe union. It can hold a value of one of its specified types at any given time. This is a big improvement over old C-style unions because it keeps track of the active type and prevents you from accessing the wrong data


Swapping with Care: A Look at counted_iterator and iter_swap in C++

First, a quick refresher. std::iter_swap is a generic algorithm that swaps the values pointed to by two iterators. It's a more flexible and safer way to swap elements than using std::swap(*it1


Mastering C++ Floating-Point Exceptions with std::feclearexcept

std::feclearexcept is a function in the <cfenv> header that helps you manage floating-point exceptions. Think of it as a "reset button" for these exceptions



Understanding and Using DefaultConstructible in C++

A type is DefaultConstructible if an object of that type can be created without any arguments. This usually means that the type has a default constructor


A Guide to C++ std::forward_list: emplace_front Explained

std::forward_list::emplace_front is a method that constructs and inserts a new element at the beginning of a std::forward_list


The C++ Portability Puzzle: Solutions for Compiler Incompatibility

C++ compiler support refers to the extent to which a specific compiler implements the features of a C++ standard (like C++11


Beyond std::isfinite: Exploring Alternatives for C++ Floating-Point Validation

The function std::isfinite from the <cmath> header is used to check if a floating-point number is finite. A finite number is any number that isn't infinity (-inf or +inf) or a "Not-a-Number" value (NaN). It's a great tool for making sure your calculations don't go off the rails


Beyond the Basics: Mastering std::mismatch in C++

std::mismatch compares two sequences of elements (like vectors, arrays, or lists) and returns a pair of iterators pointing to the first elements that don't match


Mastering C++ I/O: Common Issues and Alternatives to operator>>

Reading and Newlines When you read data with operator>>, it skips leading whitespace, including newlines. This can be a problem if you mix reading different types of data


C++ Atomics: Common Pitfalls, Memory Ordering, and Mutex Alternatives

Here's a friendly breakdown of common issues, why they happen, and sample code for both using atomics correctly and an alternative approach using locks