https://gcc.gnu.org/bugzilla/show_bug.cgi?id=113773
Bug ID: 113773 Summary: coroutines: promise deconstructed twice if throwing from return object Product: gcc Version: 12.3.0 Status: UNCONFIRMED Severity: normal Priority: P3 Component: c++ Assignee: unassigned at gcc dot gnu.org Reporter: znhihgiasy at gmail dot com Target Milestone: --- The bug is about C++ coroutines. When I throw exceptions inside the return object's type conversion operator, the promise (and maybe the coroutine state) is deconstructed twice. The C++ standard is not clear about when the conversion operator is called, and what happens when it throws. However clang's behavior is error-free and intuitive to me: The promise is deconstructed after continuing from the final suspend point and the exception is propagated to the call site of resume(). Here is a minimum example: #include <cassert> #include <coroutine> #include <iostream> struct result { operator int() { throw 42; } }; class promise { public: result get_return_object() { return {}; } std::suspend_never initial_suspend() { std::cout << "initial suspend" << std::endl; return {}; } void unhandled_exception() { std::cout << "unhandled exception" << std::endl; } std::suspend_never final_suspend() noexcept { std::cout << "final suspend" << std::endl; return {}; } void return_void() {} ~promise() { std::cout << "~promise()" << std::endl; } }; template <class... Args> struct std::coroutine_traits<int, Args...> { using promise_type = promise; }; int f() { co_return; } int main() { try { f(); } catch (int i) { assert(i == 42); std::cout << "caught 42" << std::endl; } return 0; } Compiling with `g++ --std=c++20 -g -O0 -Wall -Wextra gccbug.cpp` produced this output: initial suspend final suspend ~promise() ~promise() free(): double free detected in tcache 2 I am running G++ version 12.3.0 on x86_64 NixOS unstable with kernel 6.6.8. The behaviour is identical on gcc trunk.