Mastering std::shared_future in C++

2025-09-17

The std::shared_future is a key part of C++'s concurrency library. Unlike std::future, a shared_future can be copied, which allows multiple threads to wait for the same result. The assignment operator (=) is used to move or copy the shared state from one shared_future object to another.

Here are a few common issues you might run into

Accidental Resource Duplication
When you copy-assign a shared_future, you are creating a new object that points to the same shared state. This is the whole point of shared_future, but if you don't realize this, you might end up with unexpected behavior. For example, if you have a shared_future in a class and you copy the object, you'll have two class instances sharing the same asynchronous result. This is usually not an issue, but it's crucial to be aware of.

Attempting to Move from a const Object
You can't move from a const object. The move assignment operator (shared_future& operator=(shared_future&& other)) requires a non-const rvalue reference. If you try to move from a const shared_future, the compiler will choose the copy assignment operator instead, which can be less efficient.

Handling std::future vs. std::shared_future
This is a common point of confusion. You cannot directly assign a std::future to a std::shared_future using the assignment operator. You must use the std::future::share() method to get a shared_future from a future.

Let's look at some examples to illustrate these points and show you some common patterns.

This is the most common and intended use of std::shared_future's copy assignment. You create one future and then copy it to multiple threads.

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

void do_work(std::shared_future<int> shared_fut) {
    try {
        // The shared_future is copied into this thread
        // All threads will block until the result is ready
        int result = shared_fut.get();
        std::cout << "Thread " << std::this_thread::get_id() << " got result: " << result << std::endl;
    } catch (const std::exception& e) {
        std::cerr << "Thread " << std::this_thread::get_id() << " caught exception: " << e.what() << std::endl;
    }
}

int main() {
    std::promise<int> promise_obj;
    std::future<int> fut = promise_obj.get_future();
    std::shared_future<int> shared_fut = fut.share(); // Convert future to shared_future

    std::vector<std::thread> threads;
    for (int i = 0; i < 3; ++i) {
        // We are copy-assigning the shared_fut object to each new thread
        threads.emplace_back(do_work, shared_fut); 
    }

    // Set the value after all threads are waiting
    std::cout << "Setting the value..." << std::endl;
    promise_obj.set_value(42);

    for (auto& t : threads) {
        t.join();
    }

    return 0;
}

In this example, the line threads.emplace_back(do_work, shared_fut); is where the copy assignment happens. A new std::shared_future object is created for the do_work function, which points to the same shared state as the original shared_fut.

Move assignment is more efficient than copy assignment because it transfers the ownership of the shared state instead of creating a new reference. You typically use this when you want to pass a shared_future to a function without making a copy.

#include <iostream>
#include <future>
#include <utility> // for std::move

void process_data(std::shared_future<std::string> shared_fut) {
    std::cout << "Processing data: " << shared_fut.get() << std::endl;
}

int main() {
    std::promise<std::string> promise_obj;
    std::shared_future<std::string> source_fut = promise_obj.get_future().share();

    // The shared_future is moved to a new object. 
    // The source_fut object is now in a valid but unspecified state.
    std::shared_future<std::string> dest_fut = std::move(source_fut); 

    // This will work. The shared state is now owned by dest_fut.
    process_data(dest_fut); 

    // This is valid but will not get the result. 
    // It's in an unspecified state.
    std::cout << "source_fut is valid: " << source_fut.valid() << std::endl; 

    promise_obj.set_value("Hello, world!");

    return 0;
}

By using std::move, you're explicitly telling the compiler to use the move assignment operator. This is useful when you want to transfer ownership and want to avoid the overhead of copying.

Copy vs. Move
Remember that copy assignment (=) for std::shared_future creates a new object that points to the same shared state. Move assignment (= std::move()) transfers ownership of the shared state, making the original object invalid (or in an unspecified state).

Source of shared_future
Always remember to use std::future::share() to get a shared_future from a future. You cannot directly assign a std::future to a std::shared_future.

The Power of Sharing
The main benefit of std::shared_future is the ability to share a single asynchronous result with multiple threads. Its assignment operators are the tools you use to enable this sharing.


cpp



Mastering C++ std::shared_lock: Common Problems and Solutions

The std::shared_lock::operator bool is a convenient member function that lets you check if the std::shared_lock object owns a mutex


Beyond begin/end: Checking Sortedness with C++20 ranges::is_sorted

std::ranges::is_sorted is a handy C++ algorithm, available since C++20, that checks if a given range of elements is sorted


Understanding std::reverse_iterator and its Alternatives

The biggest thing to watch out for is the relationship between a reverse iterator and its underlying normal iterator. A std::reverse_iterator is an adaptor



Mastering std::unordered_map::find: Common Pitfalls and Alternatives

The std::unordered_map::find function is a fast and efficient way to check for the existence of a key. It's fantastic for its average O(1) time complexity


A Guide to C++ Ranges' inner and outer iterators

The most frequent issue people run into is trying to treat the dereferenced outer_iterator as a simple container of elements


std::optional in C++: A Guide to Its Operators, Troubles, and Alternatives

Think of std::optional as a little box that can either hold a value or be empty. It's super handy when you want to represent a value that might or might not exist


Mastering C++ std::iter_swap with Reverse Iterators

The most frequent mistake people make is not understanding how std::reverse_iterator works. A reverse iterator points to the element before the one it "logically" refers to


The C++ Filesystem Library: A Guide to file_status::type and Its Pitfalls

The std::filesystem::file_status::type is an enumeration that represents the type of a file system entry. It's a key part of the C++ Filesystem library


Demystifying std::perror in C++

A common mistake is trying to inspect the errno variable after calling std::perror. The std::perror function reads the current value of errno to generate its message


Beyond the Basics: C++ std::vector Memory Management

The std::vector::get_allocator method is a member function of the std::vector container in C++. Its purpose is to return a copy of the allocator object used by the vector to manage its memory