std::optional

std::optional is a C++17 standard library utility that represents an object that may or may not contain a value. It is a type-safe alternative to using special values (like nullptr or -1) to indicate “no result.”

#include <iostream>
#include <optional>
#include <string>

std::optional<std::string> find_user(int id) {
    if (id == 1) {
        return "Alice";
    } else {
        return std::nullopt; // no value
    }
}

int main() {
    std::optional<std::string> user = find_user(1);

    if (user) { // check if has value
        std::cout << "User: " << *user << std::endl;
        std::cout << "User: " << user.value() << std::endl;        
    } else {
        std::cout << "User not found\n";
    }

    std::optional<int> x;  // empty
    std::cout << x.value_or(42);  // prints 42
}
std::future

std::future is a C++ standard library class template (in ) that provides a way to access the result of an asynchronous operation. It represents a "handle" to a value that will be set at some point in the future, typically by an asynchronous task.

std::promise

std::promise is a synchronization primitive in the C++ Standard Library () that allows one thread (the producer) to provide a value or exception that another thread (the consumer) can retrieve through a corresponding std::future.

Promise Action Future Reaction
set_value(v) get() returns v
set_exception(e) get() throws e
Destructor without setting get() throws std::future_error
Value not ready yet get() blocks until ready
Feature std::promise std::async
Who manages the thread You manage manually Automatically creates/manages thread
When value is produced When you call set_value() When async task completes
Exception handling You must call set_exception() manually Automatically captured