【发布时间】:2021-07-08 17:30:51
【问题描述】:
正在发生
我想将仅移动数据存储到promise_type,并在协程中获取。我尝试从await_resume() 返回返回左值。结果是编译成功但是执行过程中出现Segmentation fault。
我该如何改进?
环境
- 操作系统:WSL2 Ubuntu 20.04
- 编译器:gcc 10.3
- 命令:g++ -std=c++20 -fcoroutines main.cpp
代码
main.cpp:
#include <iostream>
#include <coroutine>
#include <memory>
struct task
{
struct promise_type
{
using data_type = std::unique_ptr<int>;
task get_return_object() noexcept
{
return task(std::coroutine_handle<promise_type>::from_promise(*this));
}
std::suspend_never initial_suspend() const noexcept { return {}; }
void unhandled_exception() {}
std::suspend_always final_suspend() const noexcept { return {}; }
data_type data; // my data
};
void set_data(promise_type::data_type&& data) // [2] set my data
{
handle.promise().data = std::forward<promise_type::data_type>(data);
}
void resume()
{
handle.resume();
}
task(std::coroutine_handle<promise_type> handle) : handle(handle) {}
private:
std::coroutine_handle<promise_type> handle;
};
struct awaitalbe
{
bool await_ready() { return true; }
void await_suspend(std::coroutine_handle<task::promise_type> handle) { this->handle = handle; }
task::promise_type::data_type&& await_resume()
{
return std::move(handle.promise().data); // [3] get my data
}
std::coroutine_handle<task::promise_type> handle;
};
task f()
{
auto p2 = co_await awaitalbe{}; // [4] Segmentation fault here. after [3]
std::cout << (*p2) << std::endl;
}
int main(int argc, char* argv[])
{
auto task1 = f();
task::promise_type::data_type p1 = std::make_unique<task::promise_type::data_type::element_type>(10);
task1.set_data(std::move(p1)); // [1] set my data
task1.resume();
return 0;
}
【问题讨论】:
标签: c++ c++20 c++-coroutine