CKTIS / C++
co_return — completing a coroutine
co_return finishes execution of a coroutine body and delivers its result to the promise object rather than returning it directly like ordinary return. The coroutine then proceeds to final_suspend(); its state's lifetime depends on the coroutine's ownership mechanism.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
co_return;
co_return expression;
co_return braced-init-list;co_return marks coroutine completion. Its presence alone makes a function a coroutine, even without co_await or co_yield. The object returned by the function call comes from promise.get_return_object(); the co_return operand need not have the function's return type.
For a non-void expression or a braced initializer list, it calls promise.return_value(...). co_return; calls promise.return_void(). With a void operand, the expression is evaluated first, followed by return_void(). These calls must produce a result of type void.
Control then proceeds to final_suspend(). Completing the body does not automatically mean destroying the coroutine state. In the example, initial_suspend() lets the body execute immediately, return_value(int) stores 42, and final_suspend() preserves the state for inspection. The Result destructor releases it using destroy(); copying the owner is prohibited.
A coroutine body must not contain ordinary return. In C++23, falling off the end of the body is equivalent to co_return; if the promise type has a member named return_void. If that member exists but the implied call to promise.return_void() is ill-formed, the program is ill-formed. If the promise type has no member named return_void, falling off the end of the body causes undefined behavior. This entry targets C++23; the supplied site hosts an evolving working draft, not a frozen C++23 text.
Examples
#include <coroutine>
#include <exception>
#include <iostream>
struct Result {
struct promise_type;
using Handle = std::coroutine_handle<promise_type>;
struct promise_type {
int value = 0;
Result get_return_object() {
return Result{Handle::from_promise(*this)};
}
std::suspend_never initial_suspend() noexcept { return {}; }
std::suspend_always final_suspend() noexcept { return {}; }
void return_value(int n) noexcept { value = n; }
void unhandled_exception() noexcept { std::terminate(); }
};
Handle handle;
explicit Result(Handle h) noexcept : handle(h) {}
Result(const Result&) = delete;
Result& operator=(const Result&) = delete;
~Result() { handle.destroy(); }
int value() const { return handle.promise().value; }
};
Result answer() {
co_return 42;
}
int main() {
auto result = answer();
std::cout << result.value() << '\n';
}
Result
42
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.