liveBook · Manning

Co_return

As explained in Learn C++ by Example

co_return is a C++ coroutine statement that completes a coroutine and supplies its final result or completion signal.

co_return is a C++ coroutine statement that completes execution. Used without an expression, it signals completion through the coroutine's promise; unlike an ordinary return, it works with the coroutine machinery supplied by the return type. section 8.3.1 section 8.3.5

Stopping a mind-reader coroutine

A coroutine reading player input can stop when no input remains: `if (!input) { co_return; }`. Otherwise it yields the player's choice and a prediction, suspends, and later resumes with its state intact. section 8.3.2

Use co_return with these coroutine rules:

  • Add co_return, co_yield, or co_await to make a function a coroutine, then return a suitable coroutine object such as Task. section 8.3.1 section 8.3.2
  • Use a bare co_return with promise_type::return_void(); use co_return expression with promise_type::return_value instead. section 8.3.5
  • Let final_suspend mark completion so the returned Task can observe that the coroutine has finished. section 8.3.5
Listing 8.16 Our first coroutine
#include <coroutine>
struct Task;                                                #1
Task coroutine_game()                                       #2
{
    std::mt19937 gen{ std::random_device{}() };
    std::uniform_int_distribution dist{ 0, 1 };
    MindReader mr(gen, dist);
    while (true)
    {
        auto input = read_number(std::cin);
        if (!input)
        {
            co_return;                                      #3
        }
        int player_choice = input.value();
        co_yield{ player_choice , mr.get_prediction() };    #4
        mr.update(player_choice);
    }
} 

Inspect the complete coroutine flow: bare co_return exits on abandoned input, while co_yield pauses before the next iteration. section 8.3.2

How Learn C++ by Example covers it

How deep it goes
Explains bare and value-returning forms, then connects them to return_void, return_value, and final_suspend.
Examples
Demonstrates bare co_return in a mind-reader game and implements completion with return_void in promise_type.
What it assumes
Assumes basic C++ functions and returns while introducing coroutine suspension, resumption, frames, and promise boilerplate.
What you can do after
Build a coroutine that stops on a condition and wire its completion through a custom Task promise.
How it connects
Connects co_return with C++ coroutines, co_yield, co_await, promise_type, Task, and final suspension.

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.