协程承诺类型内存管理 ​

面试考点 ​

协程的内存管理是 C++20 面试中的进阶话题。面试官考察你是否理解协程帧的分配方式、promise_type 中自定义 operator new/delete 的作用、以及堆分配省略优化(HALO)的条件和原理。

核心概念 ​

当编译器遇到协程函数时,它需要分配一块内存(协程帧)来存储协程的状态:promise 对象、局部变量、挂起点索引等。默认情况下,协程帧通过 operator new 在堆上分配。但编译器在某些条件下可以将协程帧分配在调用者的栈上(HALO 优化),从而完全避免堆分配。

协程帧的分配流程 ​

步骤说明
确定帧大小编译器计算 promise + 局部变量 + 挂起点信息的总大小
查找 operator new先找 promise_type::operator new,再找全局 ::operator new
分配内存调用找到的 operator new
构造 promise在分配的内存中构造 promise_type 对象
HALO 优化编译器可能跳过堆分配,直接在栈上分配(如果能证明安全)

基本示例 ​

cpp
#include <iostream>
#include <coroutine>
#include <cstdlib>
#include <new>

// ============================
// 示例1:自定义协程帧分配
// ============================

struct TrackedTask {
    struct promise_type {
        // 自定义 operator new:追踪协程帧的分配
        void* operator new(std::size_t size) {
            std::cout << "协程帧分配: " << size << " 字节" << std::endl;
            return ::operator new(size);
        }

        // 自定义 operator delete:追踪协程帧的释放
        void operator delete(void* ptr, std::size_t size) {
            std::cout << "协程帧释放: " << size << " 字节" << std::endl;
            ::operator delete(ptr, size);
        }

        TrackedTask get_return_object() {
            return TrackedTask{
                std::coroutine_handle<promise_type>::from_promise(*this)
            };
        }

        std::suspend_always initial_suspend() { return {}; }
        std::suspend_always final_suspend() noexcept { return {}; }
        void return_void() {}
        void unhandled_exception() { std::terminate(); }
    };

    std::coroutine_handle<promise_type> handle;

    explicit TrackedTask(std::coroutine_handle<promise_type> h) : handle(h) {}
    ~TrackedTask() { if (handle) handle.destroy(); }

    TrackedTask(TrackedTask&& other) noexcept : handle(other.handle) {
        other.handle = nullptr;
    }
    TrackedTask(const TrackedTask&) = delete;

    void resume() { if (handle && !handle.done()) handle.resume(); }
};

TrackedTask tracked_coroutine() {
    int a = 10;          // 这些局部变量存在协程帧中
    int b = 20;
    double c = 3.14;
    co_await std::suspend_always{};
    std::cout << "a=" << a << " b=" << b << " c=" << c << std::endl;
}

void tracked_demo() {
    auto task = tracked_coroutine();
    // 输出类似: 协程帧分配: 80 字节(大小取决于编译器和局部变量)
    task.resume();
    // task 销毁时输出: 协程帧释放: 80 字节
}

// ============================
// 示例2:带参数的 operator new
// ============================

struct ParamTask {
    struct promise_type {
        // 编译器会把协程函数的参数传递给 operator new
        // 如果 operator new 接受额外参数,编译器会尝试匹配
        void* operator new(std::size_t size, int param1, double param2) {
            std::cout << "带参数分配: size=" << size
                      << " param1=" << param1
                      << " param2=" << param2 << std::endl;
            return ::operator new(size);
        }

        // 如果带参数版本匹配失败,回退到普通版本
        void* operator new(std::size_t size) {
            std::cout << "普通分配: size=" << size << std::endl;
            return ::operator new(size);
        }

        void operator delete(void* ptr) {
            ::operator delete(ptr);
        }

        ParamTask get_return_object() {
            return ParamTask{
                std::coroutine_handle<promise_type>::from_promise(*this)
            };
        }

        std::suspend_always initial_suspend() { return {}; }
        std::suspend_always final_suspend() noexcept { return {}; }
        void return_void() {}
        void unhandled_exception() { std::terminate(); }
    };

    std::coroutine_handle<promise_type> handle;
    explicit ParamTask(std::coroutine_handle<promise_type> h) : handle(h) {}
    ~ParamTask() { if (handle) handle.destroy(); }
    ParamTask(ParamTask&& o) noexcept : handle(o.handle) { o.handle = nullptr; }
    ParamTask(const ParamTask&) = delete;
};

// 协程函数的参数会传给 promise_type::operator new
ParamTask param_coroutine(int x, double y) {
    co_await std::suspend_always{};
    std::cout << x << ", " << y << std::endl;
}

void param_demo() {
    auto task = param_coroutine(42, 3.14);
    // 编译器尝试调用 operator new(size, 42, 3.14)
}

// ============================
// 示例3:使用内存池的协程分配
// ============================

// 简单的内存池(演示用)
class CoroutinePool {
    static constexpr size_t POOL_SIZE = 4096;
    alignas(std::max_align_t) char buffer_[POOL_SIZE];
    size_t offset_ = 0;

public:
    static CoroutinePool& instance() {
        static CoroutinePool pool;
        return pool;
    }

    void* allocate(size_t size) {
        // 简化的分配逻辑
        size_t aligned_size = (size + alignof(std::max_align_t) - 1)
                            & ~(alignof(std::max_align_t) - 1);
        if (offset_ + aligned_size > POOL_SIZE) {
            throw std::bad_alloc();
        }
        void* ptr = buffer_ + offset_;
        offset_ += aligned_size;
        std::cout << "内存池分配: " << size << " 字节" << std::endl;
        return ptr;
    }

    void deallocate(void* ptr, size_t size) {
        std::cout << "内存池释放: " << size << " 字节" << std::endl;
        // 简化:实际内存池需要更复杂的释放逻辑
    }
};

struct PoolTask {
    struct promise_type {
        // 使用内存池分配协程帧
        void* operator new(std::size_t size) {
            return CoroutinePool::instance().allocate(size);
        }

        void operator delete(void* ptr, std::size_t size) {
            CoroutinePool::instance().deallocate(ptr, size);
        }

        PoolTask get_return_object() {
            return PoolTask{
                std::coroutine_handle<promise_type>::from_promise(*this)
            };
        }

        std::suspend_always initial_suspend() { return {}; }
        std::suspend_always final_suspend() noexcept { return {}; }
        void return_void() {}
        void unhandled_exception() { std::terminate(); }
    };

    std::coroutine_handle<promise_type> handle;
    explicit PoolTask(std::coroutine_handle<promise_type> h) : handle(h) {}
    ~PoolTask() { if (handle) handle.destroy(); }
    PoolTask(PoolTask&& o) noexcept : handle(o.handle) { o.handle = nullptr; }
    PoolTask(const PoolTask&) = delete;
    void resume() { if (handle && !handle.done()) handle.resume(); }
};

PoolTask pool_coroutine() {
    co_await std::suspend_always{};
    std::cout << "从内存池分配的协程" << std::endl;
}

// ============================
// 示例4:get_return_object_on_allocation_failure
// ============================

struct SafeTask {
    struct promise_type {
        // 使用 nothrow new
        void* operator new(std::size_t size) noexcept {
            return std::malloc(size);
        }

        void operator delete(void* ptr) {
            std::free(ptr);
        }

        // 分配失败时的回退
        // 如果 operator new 返回 nullptr,编译器调用这个函数
        static SafeTask get_return_object_on_allocation_failure() {
            std::cout << "协程帧分配失败!" << std::endl;
            return SafeTask{nullptr};
        }

        SafeTask get_return_object() {
            return SafeTask{
                std::coroutine_handle<promise_type>::from_promise(*this)
            };
        }

        std::suspend_always initial_suspend() { return {}; }
        std::suspend_always final_suspend() noexcept { return {}; }
        void return_void() {}
        void unhandled_exception() { std::terminate(); }
    };

    std::coroutine_handle<promise_type> handle;
    explicit SafeTask(std::coroutine_handle<promise_type> h) : handle(h) {}
    ~SafeTask() { if (handle) handle.destroy(); }
    SafeTask(SafeTask&& o) noexcept : handle(o.handle) { o.handle = nullptr; }
    SafeTask(const SafeTask&) = delete;
    bool valid() const { return handle != nullptr; }
};

// ============================
// 示例5:HALO 优化条件
// ============================

/*
HALO(Heap Allocation eLision Optimization)允许编译器
把协程帧分配在调用者的栈上,而不是堆上。

HALO 生效的条件:
1. 协程的生命周期不超过调用者
2. 编译器能看到协程的完整定义(同一翻译单元或 LTO)
3. 协程类型足够简单(只包含 coroutine_handle)
4. begin/end/destroy 等函数可内联

典型可以 HALO 的场景:
  - Generator 在 for 循环中使用
  - 同步等待的 task

典型不能 HALO 的场景:
  - 协程句柄被存到容器中
  - 协程句柄跨函数传递
  - 协程句柄被存到全局变量
*/

// 这个用法容易被 HALO 优化
// generator<int> gen() { co_yield 1; co_yield 2; }
// for (int x : gen()) { ... }  // gen 的生命周期在循环内

// 这个用法不会被 HALO 优化
// auto g = gen();
// store_somewhere(std::move(g));  // 句柄逃逸了

int main() {
    std::cout << "=== 追踪分配 ===" << std::endl;
    tracked_demo();

    std::cout << "\n=== 带参数分配 ===" << std::endl;
    param_demo();

    std::cout << "\n=== 内存池分配 ===" << std::endl;
    {
        auto task = pool_coroutine();
        task.resume();
    }

    return 0;
}

协程帧分配策略对比 ​

策略实现方式优点缺点
默认堆分配::operator new简单,无需额外代码有分配开销
自定义 newpromise_type::operator new可追踪、可控制需要手动实现
内存池在 operator new 中使用池快速分配,减少碎片池管理复杂
HALO 优化编译器自动优化零开销不可控,依赖编译器
分配失败回退get_return_object_on_allocation_failure不抛异常需要处理失败情况

常见问题 ​

协程帧里都存了什么?

协程帧包含:resume 和 destroy 函数指针、promise_type 对象、挂起点索引、跨挂起点存活的局部变量和参数的副本、以及 co_await 表达式中的临时对象。不跨挂起点的局部变量可能被优化到栈上。

HALO 优化是标准保证的吗?

不是。标准只说"实现可能需要为协程分配额外存储",并没有要求或保证 HALO。目前 Clang 实现了 HALO(CoroElide pass),GCC 暂未实现。有提案(P2477)建议通过 promise_type::must_elide() 让程序员控制。

协程函数的参数怎么传给 operator new?

如果 promise_type 定义了接受额外参数的 operator new,编译器会把协程函数的参数转发过去。这允许你根据参数选择不同的分配策略,比如根据参数中的 allocator 分配内存。

适用场景 ​

  • 高性能异步框架(自定义分配减少延迟)
  • 嵌入式系统(内存池避免碎片)
  • 游戏引擎(预分配协程帧池)
  • 需要追踪协程内存使用的调试场景

注意事项 ​

  • 协程帧大小由编译器决定,程序员无法精确控制
  • 自定义 operator new/delete 必须成对出现
  • get_return_object_on_allocation_failure 需要 nothrow new
  • HALO 依赖编译器优化,不要假设它一定发生
  • 跨挂起点的引用和指针要注意悬空问题

总结 ​

协程帧默认通过堆分配,可以通过 promise_type::operator new 自定义分配策略(内存池、追踪、参数化分配)。HALO 是编译器优化,在协程生命周期不超过调用者且句柄不逃逸时,把帧分配在栈上。面试中要能解释协程帧的内容(promise + 局部变量 + 挂起索引)、operator new 的查找顺序(promise_type 先于全局)、HALO 优化的条件、以及分配失败的处理方式。