The co_return Keyword
Understand the use of the 'co_return' keyword in C++20.
We'll cover the following...
A coroutine uses co_return
as its return statement.
A future
Admittedly, the coroutine in the following program is the simplest coroutine. I can imagine, that still does something meaningful: it automatically stores the result of its invocation.
Press + to interact
#include <coroutine>#include <iostream>#include <memory>template<typename T>struct MyFuture {std::shared_ptr<T> value;MyFuture(std::shared_ptr<T> p): value(p) {}~MyFuture() { }T get() {return *value;}struct promise_type {std::shared_ptr<T> ptr = std::make_shared<T>();~promise_type() { }MyFuture<T> get_return_object() {return ptr;}void return_value(T v) {*ptr = v;}std::suspend_never initial_suspend() {return {};}std::suspend_never final_suspend() noexcept {return {};}void unhandled_exception() {std::exit(1);}};};MyFuture<int> createFuture() {co_return 2021;}int main() {std::cout << '\n';auto fut = createFuture();std::cout << "fut.get(): " << fut.get() << '\n';std::cout << '\n';}
MyFuture
behaves as a future, which runs immediately. ...