C++ 20

发布于 2020-11-08  294 次阅读


综述

详细内容

特性

协程 Coroutine

https://en.cppreference.com/w/cpp/language/coroutines
A coroutine is a function that can suspend execution to be resumed later. Coroutines are stackless: they suspend execution by returning to the caller and the data that is required to resume execution is stored separately from the stack. This allows for sequential code that executes asynchronously (e.g. to handle non-blocking I/O without explicit callbacks), and also supports algorithms on lazy-computed infinite sequences and other uses.

A function is a coroutine if its definition does any of the following:

uses the co_await operator to suspend execution until resumed

task<> tcp_echo_server() {
  char data[1024];
  for (;;) {
    size_t n = co_await socket.async_read_some(buffer(data));
    co_await async_write(socket, buffer(data, n));
  }
}

uses the keyword co_yield to suspend execution returning a value

generator<int> iota(int n = 0) {
  while(true)
    co_yield n++;
}

uses the keyword co_return to complete execution returning a value

lazy<int> f() {
  co_return 7;
}

Every coroutine must have a return type that satisfies a number of requirements, noted below.


朝闻道,夕死可矣