std::future 不能直接链式调用 then() 因其不可复制、无内置回调机制,强行封装易致生命周期失控或重复 get();需手写 promise/Future 结构,含 shared_state、Promise、Future 三部分,并用 shared_ptr 管理状态、mutex 保护写入、vector 存回调。

为什么 std::future 不能直接链式调用 then()
标准库的 std::future 没有 then() 方法,且是**不可复制**(仅可移动),无法在回调中安全持有并转发。强行包装会导致生命周期失控、std::future::get() 被重复调用或阻塞主线程。真正可组合的异步任务需要自己管理状态流转和执行上下文。
手写 Promise/Future 的最小可行结构
核心是三部分:共享状态(shared_state)、Promise(写端)、Future(读端 + then)。所有回调必须延迟到前序任务完成后再调度,且每个 then 返回新 Future。
-
shared_state用std::shared_ptr管理,含std::optional存结果、std::mutex保护写入、std::vector<:function>>存待触发的then回调 -
Promise::set_value(T)锁定后设置值,并逐个调用已注册的回调(注意:回调里可能再调then,所以需拷贝回调列表) -
Future::then(F&& f)注册一个新回调,该回调接收当前值、返回Future,内部自动把返回的Future的shared_state和当前绑定
then() 回调如何处理返回值类型和异常
模板推导必须支持 f 返回 T、Future 或抛异常。关键点是:无论 f 返回什么,都要统一“降级”为 Future;异常要捕获并存入下游 shared_state。
template auto then(F&& f) && { using R = std::invoke_result_t; auto next_promise = Promise>{}; auto next_future = next_promise.get_future(); state_->add_continuation([p = std::move(next_promise), f = std::forward(f)](auto&& val) mutable { try { if constexpr (std::is_same_v>>) { auto inner_fut = f(std::forward(val)); inner_fut.state_->link_to(p.state_); // 链式转发完成状态 } else { p.set_value(f(std::forward(val))); } } catch (...) { p.set_exception(std::current_exception()); } }); return std::move(next_future); }
实际使用时最容易漏掉的三件事
不是语法问题,而是语义陷阱:
立即学习“C++免费学习笔记(深入)”;
- 没有显式调度策略:所有
then回调默认在「前序任务完成的线程」执行,若前序是 IO 线程而你想切到 GUI 线程,必须手动加post(ui_executor, ...) -
Future移动后原对象变空,但state_仍被其他Future引用,所以不能靠析构来释放资源 —— 必须用引用计数保证shared_state生命周期 - 循环引用风险:若
then回调里又捕获了当前Future(比如用于重试),就会导致shared_state永远不销毁,必须用weak_ptr或明确设计生命周期边界
c++20 的 std::jthread 和协程能简化调度,但 then() 的本质逻辑——状态传递、错误传播、类型擦除——还是得自己兜底。别指望靠一层 wrapper 就完全复刻 rust 的 async/await 流畅度。