根据博客文章C++ 协程:了解对称传输, 对称传输允许您挂起一个协程并恢复另一个协程,而无需消耗任何额外的堆栈空间。这可以防止堆栈溢出,当协程包含循环和co_await可能在该循环体内同步完成的任务时,可能会发生堆栈溢出。
尽管以下代码示例使用对称传输,但它会因堆栈溢出而崩溃。请注意,下面的代码是重现堆栈溢出的最小示例:例如,如果我Type在头文件中包含类型析构函数的定义,则不会出现堆栈溢出。
// type.h
#pragma once
struct Type {
~Type();
};
Run Code Online (Sandbox Code Playgroud)
// type.cc
#include "type.h"
Type::~Type() {}
Run Code Online (Sandbox Code Playgroud)
// main.cc
#include <cstdint>
#include <exception>
#include <type_traits>
#include <utility>
#include "type.h"
#if __has_include(<coroutine>) // when using g++
#include <coroutine>
namespace coro {
using std::coroutine_handle;
using std::noop_coroutine;
using std::suspend_always;
} // namespace coro
#elif __has_include(<experimental/coroutine>) // when using clang++
#include <experimental/coroutine>
namespace coro {
using std::experimental::coroutine_handle;
using std::experimental::noop_coroutine;
using std::experimental::suspend_always;
} // namespace …Run Code Online (Sandbox Code Playgroud)