Request Short Link
C++ 98
C++ 11
C++ 14
C++ 17
C++ 20
C++ 23
C++ 2c
for-loops as while-loops
array subscription
Show all implicit casts
Show all template parameters of a CallExpr
Use libc++
Transform std::initializer_list
Show noexcept internals
Show padding information
Show coroutine transformation
Show C++ to C transformation
Show object lifetime
Default
15
18
20
22
26
More
GitHub
Patreon
Issues
About
Policies
Examples
C++ Insights @ YouTube
Settings
Version
None
×
Made by
Andreas Fertig
Powered by
Flask
and
CodeMirror
Source:
#include <memory> #include <coroutine> struct callable_data { std::coroutine_handle<> handle; int data; ~callable_data() { if (handle) { handle.destroy(); } } }; static int counter = 0; static std::coroutine_handle<> current_caller; struct test_pending_awaitable { bool await_ready() noexcept { return false; } int await_resume() noexcept { return ++counter; } void await_suspend(std::coroutine_handle<> caller) noexcept { current_caller = caller; } }; class callable_promise { public: callable_promise(std::shared_ptr<callable_data> ref): data_(ref) {} struct promise_type { std::shared_ptr<callable_data> data = std::make_shared<callable_data>(); void return_value(int value) { data->data = value; } auto get_return_object() noexcept { return callable_promise{data}; } struct initial_awaitable { inline bool await_ready() const noexcept { return false; } inline void await_resume() const noexcept { } inline bool await_suspend(std::coroutine_handle<promise_type> caller) noexcept { caller.promise().data->handle = caller; return false; } }; initial_awaitable initial_suspend() noexcept { return {}; } std::suspend_always final_suspend() noexcept { return {}; } void unhandled_exception() { throw; } }; inline const int data() const noexcept { return data_->data; } inline void start() { if (data_->handle && !data_->handle.done()) { data_->handle.resume(); } } protected: std::shared_ptr<callable_data> data_; }; callable_promise do_coroutine_func() { auto x1 = co_await test_pending_awaitable{}; test_pending_awaitable y; auto x2 = co_await y; co_return x1 + x2; } int call_coroutine_func() { { auto f = do_coroutine_func(); f.start(); current_caller.resume(); ++ counter; current_caller.resume(); } return counter; }
Insight:
Console: